Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Port the following code from Delphi to Go with equivalent syntax and logic. | function Factorize(n : Integer) : String;
begin
if n <= 1 then
Exit('1');
var k := 2;
while n >= k do begin
while (n mod k) = 0 do begin
Result += ' * '+IntToStr(k);
n := n div k;
end;
Inc(k);
end;
Result:=SubStr(Result, 4);
end;
var i : Integer;
for i := 1 to 22 do
PrintLn(IntToStr(i) + ': ' + Factorize(i));
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Please provide an equivalent version of this Elixir code in C. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Translate the given Elixir code snippet into C# without altering its behavior. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Convert the following code from Elixir to C++, ensuring the logic remains intact. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Please provide an equivalent version of this Elixir code in Java. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Convert this Elixir snippet to Python and keep its semantics consistent. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Write the same code in VB as shown below in Elixir. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Produce a language-to-language conversion: from Elixir to Go, same semantics. | defmodule RC do
def factor(n), do: factor(n, 2, [])
def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact])
def factor(n, i, fact) do
if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]),
else: factor(n, i+1, fact)
end
end
Enum.each(1..20, fn n ->
IO.puts "
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Generate an equivalent C version of this F# code. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Transform the following F# implementation into C#, maintaining the same output and logic. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Transform the following F# implementation into C++, maintaining the same output and logic. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Port the following code from F# to Java with equivalent syntax and logic. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Write the same algorithm in Python as shown in this F# implementation. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Rewrite the snippet below in VB so it works the same as the original F# code. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Write the same code in Go as shown below in F#. | let factorsOf (num) =
Seq.unfold (fun (f, n) ->
let rec genFactor (f, n) =
if f > n then None
elif n % f = 0 then Some (f, (f, n/f))
else genFactor (f+1, n)
genFactor (f, n)) (2, num)
let showLines = Seq.concat (seq { yield seq{ yield(Seq.singleton 1)}; yield (Seq.skip 2 (Seq.initInfinite factorsOf))})
showLines |> Seq.iteri (fun i f -> printfn "%d = %s" (i+1) (String.Join(" * ", Seq.toArray f)))
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Produce a language-to-language conversion: from Factor to C, same semantics. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Factor, keeping it the same logically? | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Port the following code from Factor to C++ with equivalent syntax and logic. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Rewrite the snippet below in Java so it works the same as the original Factor code. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Translate the given Factor code snippet into Python without altering its behavior. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Port the provided Factor code into VB while preserving the original functionality. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Rewrite this program in Go while keeping its functionality equivalent to the Factor version. | USING: io kernel math.primes.factors math.ranges prettyprint
sequences ;
: .factors ( n -- )
dup pprint ": " write factors
[ " × " write ] [ pprint ] interleave nl ;
"1: 1" print 2 20 [a,b] [ .factors ] each
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Transform the following Forth implementation into C, maintaining the same output and logic. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Produce a language-to-language conversion: from Forth to C#, same semantics. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Can you help me rewrite this code in C++ instead of Forth, keeping it the same logically? | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Preserve the algorithm and functionality while converting the code from Forth to Java. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Convert this Forth block to Python, preserving its control flow and logic. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Please provide an equivalent version of this Forth code in VB. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Convert this Forth snippet to Go and keep its semantics consistent. | : .factors
2
begin 2dup dup * >=
while 2dup /mod swap
if drop 1+ 1 or
else -rot nip dup . ." x "
then
repeat
drop . ;
: main
." 1 : 1" cr
1+ 2 ?do i . ." : " i .factors cr loop ;
15 main bye
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Generate an equivalent C# version of this Fortran code. |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Convert this Fortran snippet to C++ and keep its semantics consistent. |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Write the same algorithm in C as shown in this Fortran implementation. |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in Java instead of Fortran, keeping it the same logically? |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Can you help me rewrite this code in Python instead of Fortran, keeping it the same logically? |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Write the same algorithm in VB as shown in this Fortran implementation. |
module prime_mod
integer, dimension(:), allocatable :: sieve_table
private :: PrimeQ
contains
subroutine sieve(n)
integer, intent(in) :: n
integer :: status, i, j
if ((n .lt. 1) .or. allocated(sieve_table)) deallocate(sieve_table)
if (n .lt. 1) return
allocate(sieve_table(n), stat=status)
if (status .ne. 0) stop 'cannot allocate space'
sieve_table(1) = 1
do i=2,int(sqrt(real(n)))+1
if (sieve_table(i) .eq. 0) then
do j = i*i, n, i
sieve_table(j) = i
end do
end if
end do
end subroutine sieve
subroutine check_sieve(n)
integer, intent(in) :: n
if (.not. (allocated(sieve_table) .and. ((1 .le. n) .and. (n .le. size(sieve_table))))) stop 'Call sieve first'
end subroutine check_sieve
logical function isPrime(p)
integer, intent(in) :: p
call check_sieve(p)
isPrime = PrimeQ(p)
end function isPrime
logical function isComposite(p)
integer, intent(in) :: p
isComposite = .not. isPrime(p)
end function isComposite
logical function PrimeQ(p)
integer, intent(in) :: p
PrimeQ = sieve_table(p) .eq. 0
end function PrimeQ
subroutine prime_factors(p, rv, n)
integer, intent(in) :: p
integer, dimension(:), intent(out) :: rv
integer, intent(out) :: n
integer :: i, m
call check_sieve(p)
m = p
i = 1
if (p .ne. 1) then
do while ((.not. PrimeQ(m)) .and. (i .lt. size(rv)))
rv(i) = sieve_table(m)
m = m/rv(i)
i = i+1
end do
end if
if (i .le. size(rv)) rv(i) = m
n = i
end subroutine prime_factors
end module prime_mod
program count_in_factors
use prime_mod
integer :: i, n
integer, dimension(8) :: factors
call sieve(40)
do i=1,40
factors = 0
call prime_factors(i, factors, n)
write(6,*)'assert',i,'= */',factors(:n)
end do
call sieve(0)
end program count_in_factors
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Please provide an equivalent version of this Groovy code in C. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Produce a language-to-language conversion: from Groovy to C#, same semantics. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Groovy. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Translate the given Groovy code snippet into Java without altering its behavior. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Generate a Python translation of this Groovy snippet without changing its computational steps. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Translate this program into VB but keep the logic exactly as in Groovy. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Translate the given Groovy code snippet into Go without altering its behavior. | def factors(number) {
if (number == 1) {
return [1]
}
def factors = []
BigInteger value = number
BigInteger possibleFactor = 2
while (possibleFactor <= value) {
if (value % possibleFactor == 0) {
factors << possibleFactor
value /= possibleFactor
} else {
possibleFactor++
}
}
factors
}
Number.metaClass.factors = { factors(delegate) }
((1..10) + (6351..6359)).each { number ->
println "$number = ${number.factors().join(' x ')}"
}
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Please provide an equivalent version of this Haskell code in C. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Port the following code from Haskell to C# with equivalent syntax and logic. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Produce a functionally identical C++ code for the snippet given in Haskell. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Produce a functionally identical Java code for the snippet given in Haskell. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Produce a language-to-language conversion: from Haskell to Python, same semantics. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Port the provided Haskell code into VB while preserving the original functionality. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Write a version of this Haskell function in Go with identical behavior. | import Data.List (intercalate)
showFactors n = show n ++ " = " ++ (intercalate " * " . map show . factorize) n
showFactors = ((++) . show) <*> ((" = " ++) . intercalate " * " . map show . factorize)
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Translate this program into C but keep the logic exactly as in Icon. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Can you help me rewrite this code in C# instead of Icon, keeping it the same logically? | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Change the programming language of this snippet from Icon to C++ without modifying what it does. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Translate the given Icon code snippet into Java without altering its behavior. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Keep all operations the same but rewrite the snippet in Python. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Write the same algorithm in VB as shown in this Icon implementation. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Port the following code from Icon to Go with equivalent syntax and logic. | procedure main()
write("Press ^C to terminate")
every f := [i:= 1] | factors(i := seq(2)) do {
writes(i," : [")
every writes(" ",!f|"]\n")
}
end
link factors
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Change the programming language of this snippet from J to C without modifying what it does. | q:
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Write the same code in C# as shown below in J. | q:
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Transform the following J implementation into C++, maintaining the same output and logic. | q:
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Preserve the algorithm and functionality while converting the code from J to Java. | q:
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Port the following code from J to Python with equivalent syntax and logic. | q:
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Produce a language-to-language conversion: from J to VB, same semantics. | q:
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Generate a Go translation of this J snippet without changing its computational steps. | q:
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Preserve the algorithm and functionality while converting the code from Julia to C. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Port the provided Julia code into C# while preserving the original functionality. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Convert the following code from Julia to C++, ensuring the logic remains intact. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Generate an equivalent Java version of this Julia code. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Julia version. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Convert this Julia block to VB, preserving its control flow and logic. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Write a version of this Julia function in Go with identical behavior. | using Primes, Printf
function strfactor(n::Integer)
n > -2 || return "-1 × " * strfactor(-n)
isprime(n) || n < 2 && return dec(n)
f = factor(Vector{typeof(n)}, n)
return join(f, " × ")
end
lo, hi = -4, 40
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Produce a functionally identical C code for the snippet given in Lua. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Convert this Lua snippet to Java and keep its semantics consistent. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Preserve the algorithm and functionality while converting the code from Lua to Python. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Produce a functionally identical VB code for the snippet given in Lua. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Write the same algorithm in Go as shown in this Lua implementation. | function factorize( n )
if n == 1 then return {1} end
local k = 2
res = {}
while n > 1 do
while n % k == 0 do
res[#res+1] = k
n = n / k
end
k = k + 1
end
return res
end
for i = 1, 22 do
io.write( i, ": " )
fac = factorize( i )
io.write( fac[1] )
for j = 2, #fac do
io.write( " * ", fac[j] )
end
print ""
end
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Translate the given Mathematica code snippet into C without altering its behavior. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Transform the following Mathematica implementation into C#, maintaining the same output and logic. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Produce a functionally identical Java code for the snippet given in Mathematica. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Port the following code from Mathematica to Python with equivalent syntax and logic. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Translate the given Mathematica code snippet into VB without altering its behavior. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Generate an equivalent Go version of this Mathematica code. | n = 2;
While[n < 100,
Print[Row[Riffle[Flatten[Map[Apply[ConstantArray, #] &, FactorInteger[n]]],"*"]]];
n++]
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Convert this Nim block to C, preserving its control flow and logic. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Please provide an equivalent version of this Nim code in C#. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Translate this program into C++ but keep the logic exactly as in Nim. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Produce a language-to-language conversion: from Nim to Java, same semantics. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Can you help me rewrite this code in Python instead of Nim, keeping it the same logically? | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Write a version of this Nim function in VB with identical behavior. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Write a version of this Nim function in Go with identical behavior. | var primes = newSeq[int]()
proc getPrime(idx: int): int =
if idx >= primes.len:
if primes.len == 0:
primes.add 2
primes.add 3
var last = primes[primes.high]
while idx >= primes.len:
last += 2
for i, p in primes:
if p * p > last:
primes.add last
break
if last mod p == 0:
break
return primes[idx]
for x in 1 ..< int32.high.int:
stdout.write x, " = "
var n = x
var first = true
for i in 0 ..< int32.high:
let p = getPrime(i)
while n mod p == 0:
n = n div p
if not first: stdout.write " x "
first = false
stdout.write p
if n <= p * p:
break
if first > 0: echo n
elif n > 1: echo " x ", n
else: echo ""
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Port the following code from OCaml to C with equivalent syntax and logic. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the OCaml version. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| #include <iostream>
#include <iomanip>
using namespace std;
void getPrimeFactors( int li )
{
int f = 2; string res;
if ( li == 1 ) res = "1";
else
{
while ( true )
{
if( !( li % f ) )
{
res += to_string(f);
li /= f; if( li == 1 ) break;
res += " x ";
}
else f++;
}
}
cout << res << "\n";
}
int main( int argc, char* argv[] )
{
for ( int x = 1; x < 101; x++ )
{
cout << right << setw( 4 ) << x << ": ";
getPrimeFactors( x );
}
cout << 2144 << ": "; getPrimeFactors( 2144 );
cout << "\n\n";
return system( "pause" );
}
|
Preserve the algorithm and functionality while converting the code from OCaml to Java. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| public class CountingInFactors{
public static void main(String[] args){
for(int i = 1; i<= 10; i++){
System.out.println(i + " = "+ countInFactors(i));
}
for(int i = 9991; i <= 10000; i++){
System.out.println(i + " = "+ countInFactors(i));
}
}
private static String countInFactors(int n){
if(n == 1) return "1";
StringBuilder sb = new StringBuilder();
n = checkFactor(2, n, sb);
if(n == 1) return sb.toString();
n = checkFactor(3, n, sb);
if(n == 1) return sb.toString();
for(int i = 5; i <= n; i+= 2){
if(i % 3 == 0)continue;
n = checkFactor(i, n, sb);
if(n == 1)break;
}
return sb.toString();
}
private static int checkFactor(int mult, int n, StringBuilder sb){
while(n % mult == 0 ){
if(sb.length() > 0) sb.append(" x ");
sb.append(mult);
n /= mult;
}
return n;
}
}
|
Transform the following OCaml implementation into Python, maintaining the same output and logic. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| from functools import lru_cache
primes = [2, 3, 5, 7, 11, 13, 17]
@lru_cache(maxsize=2000)
def pfactor(n):
if n == 1:
return [1]
n2 = n // 2 + 1
for p in primes:
if p <= n2:
d, m = divmod(n, p)
if m == 0:
if d > 1:
return [p] + pfactor(d)
else:
return [p]
else:
if n > primes[-1]:
primes.append(n)
return [n]
if __name__ == '__main__':
mx = 5000
for n in range(1, mx + 1):
factors = pfactor(n)
if n <= 10 or n >= mx - 20:
print( '%4i %5s %s' % (n,
'' if factors != [n] or n == 1 else 'prime',
'x'.join(str(i) for i in factors)) )
if n == 11:
print('...')
print('\nNumber of primes gathered up to', n, 'is', len(primes))
print(pfactor.cache_info())
|
Generate an equivalent VB version of this OCaml code. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| Function CountFactors(n)
If n = 1 Then
CountFactors = 1
Else
arrP = Split(ListPrimes(n)," ")
Set arrList = CreateObject("System.Collections.ArrayList")
divnum = n
Do Until divnum = 1
For i = 0 To UBound(arrP)-1
If divnum = 1 Then
Exit For
ElseIf divnum Mod arrP(i) = 0 Then
divnum = divnum/arrP(i)
arrList.Add arrP(i)
End If
Next
Loop
arrList.Sort
For i = 0 To arrList.Count - 1
If i = arrList.Count - 1 Then
CountFactors = CountFactors & arrList(i)
Else
CountFactors = CountFactors & arrList(i) & " * "
End If
Next
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
Function ListPrimes(n)
ListPrimes = ""
For i = 1 To n
If IsPrime(i) Then
ListPrimes = ListPrimes & i & " "
End If
Next
End Function
WScript.StdOut.Write "2 = " & CountFactors(2)
WScript.StdOut.WriteLine
WScript.StdOut.Write "2144 = " & CountFactors(2144)
WScript.StdOut.WriteLine
|
Convert this OCaml snippet to Go and keep its semantics consistent. | open Big_int
let prime_decomposition x =
let rec inner c p =
if lt_big_int p (square_big_int c) then
[p]
else if eq_big_int (mod_big_int p c) zero_big_int then
c :: inner c (div_big_int p c)
else
inner (succ_big_int c) p
in
inner (succ_big_int (succ_big_int zero_big_int)) x
let () =
let rec aux v =
let ps = prime_decomposition v in
print_string (string_of_big_int v);
print_string " = ";
print_endline (String.concat " x " (List.map string_of_big_int ps));
aux (succ_big_int v)
in
aux unit_big_int
| package main
import "fmt"
func main() {
fmt.Println("1: 1")
for i := 2; ; i++ {
fmt.Printf("%d: ", i)
var x string
for n, f := i, 2; n != 1; f++ {
for m := n % f; m == 0; m = n % f {
fmt.Print(x, f)
x = "×"
n /= f
}
}
fmt.Println()
}
}
|
Port the following code from Pascal to C with equivalent syntax and logic. | program CountInFactors(output);
type
TdynArray = array of integer;
function factorize(number: integer): TdynArray;
var
k: integer;
begin
if number = 1 then
begin
setlength(Result, 1);
Result[0] := 1
end
else
begin
k := 2;
while number > 1 do
begin
while number mod k = 0 do
begin
setlength(Result, length(Result) + 1);
Result[high(Result)] := k;
number := number div k;
end;
inc(k);
end;
end
end;
var
i, j: integer;
fac: TdynArray;
begin
for i := 1 to 22 do
begin
write(i, ': ' );
fac := factorize(i);
write(fac[0]);
for j := 1 to high(fac) do
write(' * ', fac[j]);
writeln;
end;
end.
| #include <stdio.h>
#include <stdlib.h>
typedef unsigned long long ULONG;
ULONG get_prime(int idx)
{
static long n_primes = 0, alloc = 0;
static ULONG *primes = 0;
ULONG last, p;
int i;
if (idx >= n_primes) {
if (n_primes >= alloc) {
alloc += 16;
primes = realloc(primes, sizeof(ULONG) * alloc);
}
if (!n_primes) {
primes[0] = 2;
primes[1] = 3;
n_primes = 2;
}
last = primes[n_primes-1];
while (idx >= n_primes) {
last += 2;
for (i = 0; i < n_primes; i++) {
p = primes[i];
if (p * p > last) {
primes[n_primes++] = last;
break;
}
if (last % p == 0) break;
}
}
}
return primes[idx];
}
int main()
{
ULONG n, x, p;
int i, first;
for (x = 1; ; x++) {
printf("%lld = ", n = x);
for (i = 0, first = 1; ; i++) {
p = get_prime(i);
while (n % p == 0) {
n /= p;
if (!first) printf(" x ");
first = 0;
printf("%lld", p);
}
if (n <= p * p) break;
}
if (first) printf("%lld\n", n);
else if (n > 1) printf(" x %lld\n", n);
else printf("\n");
}
return 0;
}
|
Please provide an equivalent version of this Pascal code in C#. | program CountInFactors(output);
type
TdynArray = array of integer;
function factorize(number: integer): TdynArray;
var
k: integer;
begin
if number = 1 then
begin
setlength(Result, 1);
Result[0] := 1
end
else
begin
k := 2;
while number > 1 do
begin
while number mod k = 0 do
begin
setlength(Result, length(Result) + 1);
Result[high(Result)] := k;
number := number div k;
end;
inc(k);
end;
end
end;
var
i, j: integer;
fac: TdynArray;
begin
for i := 1 to 22 do
begin
write(i, ': ' );
fac := factorize(i);
write(fac[0]);
for j := 1 to high(fac) do
write(' * ', fac[j]);
writeln;
end;
end.
| using System;
using System.Collections.Generic;
namespace prog
{
class MainClass
{
public static void Main (string[] args)
{
for( int i=1; i<=22; i++ )
{
List<int> f = Factorize(i);
Console.Write( i + ": " + f[0] );
for( int j=1; j<f.Count; j++ )
{
Console.Write( " * " + f[j] );
}
Console.WriteLine();
}
}
public static List<int> Factorize( int n )
{
List<int> l = new List<int>();
if ( n == 1 )
{
l.Add(1);
}
else
{
int k = 2;
while( n > 1 )
{
while( n % k == 0 )
{
l.Add( k );
n /= k;
}
k++;
}
}
return l;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.