Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Maintain the same structure and functionality when rewriting this 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.
#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 Pascal to Java, same semantics.
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.
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 Pascal snippet without changing its computational steps.
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.
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())
Maintain the same structure and functionality when rewriting this code in VB.
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.
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 functionally identical Go code for the snippet given in Pascal.
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.
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() } }
Keep all operations the same but rewrite the snippet in C.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
#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; }
Change the following Perl code into C# without altering its purpose.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
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 Perl.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
#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 Perl block to Java, preserving its control flow and logic.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
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 Perl to Python.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
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 Perl function in VB with identical behavior.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
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 Perl snippet without changing its computational steps.
use ntheory qw/factor/; print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010;
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 PowerShell.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
#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 PowerShell to C# with equivalent syntax and logic.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
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; } } }
Ensure the translated C++ code behaves exactly like the original PowerShell snippet.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
#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 Java as shown in this PowerShell implementation.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
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; } }
Change the programming language of this snippet from PowerShell to Python without modifying what it does.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
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())
Preserve the algorithm and functionality while converting the code from PowerShell to VB.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
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 PowerShell version.
function eratosthenes ($n) { if($n -ge 1){ $prime = @(1..($n+1) | foreach{$true}) $prime[1] = $false $m = [Math]::Floor([Math]::Sqrt($n)) for($i = 2; $i -le $m; $i++) { if($prime[$i]) { for($j = $i*$i; $j -le $n; $j += $i) { $prime[$j] = $false } } } 1..$n | where{$prime[$_]} } else { "$n must be equal or greater than 1" } } function prime-decomposition ($n) { $array = eratosthenes $n $prime = @() foreach($p in $array) { while($n%$p -eq 0) { $n /= $p $prime += @($p) } } $prime } $OFS = " x " "$(prime-decomposition 2144)" "$(prime-decomposition 100)" "$(prime-decomposition 12)"
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 R to C, same semantics.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
#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; }
Change the programming language of this snippet from R to C# without modifying what it does.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
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; } } }
Rewrite this program in C++ while keeping its functionality equivalent to the R version.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
#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" ); }
Maintain the same structure and functionality when rewriting this code in Java.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
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 R implementation.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
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 this program in VB while keeping its functionality equivalent to the R version.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
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 R code in Go.
findfactors <- function(num) { x <- c() p1<- 2 p2 <- 3 everyprime <- num while( everyprime != 1 ) { while( everyprime%%p1 == 0 ) { x <- c(x, p1) everyprime <- floor(everyprime/ p1) } p1 <- p2 p2 <- p2 + 2 } x } count_in_factors=function(x){ primes=findfactors(x) x=c(1) for (i in 1:length(primes)) { x=paste(primes[i],"x",x) } return(x) } count_in_factors(72)
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() } }
Keep all operations the same but rewrite the snippet in C.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
#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 Racket version.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
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; } } }
Generate a C++ translation of this Racket snippet without changing its computational steps.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
#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 a Java translation of this Racket snippet without changing its computational steps.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
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 a version of this Racket function in Python with identical behavior.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
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())
Can you help me rewrite this code in VB instead of Racket, keeping it the same logically?
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
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 Racket code.
#lang typed/racket (require math/number-theory) (define (factorise-as-primes [n : Natural]) (if (= n 1) '(1) (let ((F (factorize n))) (append* (for/list : (Listof (Listof Natural)) ((f (in-list F))) (make-list (second f) (first f))))))) (define (factor-count [start-inc : Natural] [end-inc : Natural]) (for ((i : Natural (in-range start-inc (add1 end-inc)))) (define f (string-join (map number->string (factorise-as-primes i)) " × ")) (printf "~a:\t~a~%" i f))) (factor-count 1 22) (factor-count 2140 2150)
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 REXX to C with equivalent syntax and logic.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
#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 REXX code into C# while preserving the original functionality.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
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 the given REXX code snippet into C++ without altering its behavior.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
#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 this program in Java while keeping its functionality equivalent to the REXX version.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
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 the following code from REXX to Python, ensuring the logic remains intact.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
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 REXX code in VB.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
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
Preserve the algorithm and functionality while converting the code from REXX to Go.
options replace format comments java crossref symbols nobinary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method factor(val) public static rv = 1 if val > 1 then do rv = '' loop n_ = val until n_ = 1 parse checkFactor(2, n_, rv) n_ rv if n_ = 1 then leave n_ parse checkFactor(3, n_, rv) n_ rv if n_ = 1 then leave n_ loop m_ = 5 to n_ by 2 until n_ = 1 if m_ // 3 = 0 then iterate m_ parse checkFactor(m_, n_, rv) n_ rv end m_ end n_ end return rv -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method checkFactor(mult = long, n_ = long, fac) private static binary msym = 'x' loop while n_ // mult = 0 fac = fac msym mult n_ = n_ % mult end fac = (fac.strip).strip('l', msym).space return n_ fac -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static -- input is a list of pairs of numbers - no checking is done if arg = '' then arg = '1 11 89 101 1000 1020 10000 10010' loop while arg \= '' parse arg lv rv arg say say '-'.copies(60) say lv.right(8) 'to' rv say '-'.copies(60) loop fv = lv to rv fac = factor(fv) pv = '' if fac.words = 1 & fac \= 1 then pv = '<prime>' say fv.right(8) '=' fac pv end fv end return
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 Ruby code snippet into C without altering its behavior.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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; }
Translate this program into C# but keep the logic exactly as in Ruby.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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; } } }
Transform the following Ruby implementation into C++, maintaining the same output and logic.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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" ); }
Port the following code from Ruby to Java with equivalent syntax and logic.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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; } }
Port the provided Ruby code into Python while preserving the original functionality.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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 Ruby block to VB, preserving its control flow and logic.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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
Please provide an equivalent version of this Ruby code in Go.
require 'optparse' require 'prime' maximum = 10 OptionParser.new do |o| o.banner = "Usage: o.on("-m MAXIMUM", Integer, "Count up to MAXIMUM [ o.parse! rescue ($stderr.puts $!, o; exit 1) ($stderr.puts o; exit 1) unless ARGV.size == 0 end puts "1 is 1" unless maximum < 1 2.upto(maximum) do |i| f = i.prime_division.map! do |factor, exponent| ([factor] * exponent).join " x " end.join " x " puts " 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() } }
Can you help me rewrite this code in C instead of Scala, keeping it the same logically?
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
#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 this program into C# but keep the logic exactly as in Scala.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
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 Scala.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
#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" ); }
Keep all operations the same but rewrite the snippet in Java.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
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 Scala to Python with equivalent syntax and logic.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
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 Scala code into VB while preserving the original functionality.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
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
Maintain the same structure and functionality when rewriting this code in Go.
fun isPrime(n: Int) : Boolean { if (n < 2) return false if (n % 2 == 0) return n == 2 if (n % 3 == 0) return n == 3 var d = 5 while (d * d <= n) { if (n % d == 0) return false d += 2 if (n % d == 0) return false d += 4 } return true } fun getPrimeFactors(n: Int): List<Int> { val factors = mutableListOf<Int>() if (n < 1) return factors if (n == 1 || isPrime(n)) { factors.add(n) return factors } var factor = 2 var nn = n while (true) { if (nn % factor == 0) { factors.add(factor) nn /= factor if (nn == 1) return factors if (isPrime(nn)) factor = nn } else if (factor >= 3) factor += 2 else factor = 3 } } fun main(args: Array<String>) { val list = (MutableList(22) { it + 1 } + 2144) + 6358 for (i in list) println("${"%4d".format(i)} = ${getPrimeFactors(i).joinToString(" * ")}") }
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 Swift to C, same semantics.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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; }
Rewrite the snippet below in C# so it works the same as the original Swift code.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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; } } }
Change the programming language of this snippet from Swift to C++ without modifying what it does.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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" ); }
Port the following code from Swift to Java with equivalent syntax and logic.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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; } }
Write a version of this Swift function in Python with identical behavior.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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())
Write the same algorithm in VB as shown in this Swift implementation.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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
Produce a functionally identical Go code for the snippet given in Swift.
extension BinaryInteger { @inlinable public func primeDecomposition() -> [Self] { guard self > 1 else { return [] } func step(_ x: Self) -> Self { return 1 + (x << 2) - ((x >> 1) << 1) } let maxQ = Self(Double(self).squareRoot()) var d: Self = 1 var q: Self = self & 1 == 0 ? 2 : 3 while q <= maxQ && self % q != 0 { q = step(d) d += 1 } return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] } } for i in 1...20 { if i == 1 { print("1 = 1") } else { print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " 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() } }
Write a version of this Tcl function in C with identical behavior.
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
#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 Tcl.
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
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 Tcl, keeping it the same logically?
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
#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 a Java translation of this Tcl snippet without changing its computational steps.
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
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 functionally identical Python code for the snippet given in Tcl.
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
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())
Can you help me rewrite this code in VB instead of Tcl, keeping it the same logically?
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
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 Tcl code.
package require Tcl 8.5 namespace eval prime { variable primes [list 2 3 5 7 11] proc restart {} { variable index -1 variable primes variable current [lindex $primes end] } proc get_next_prime {} { variable primes variable index if {$index < [llength $primes]-1} { return [lindex $primes [incr index]] } variable current while 1 { incr current 2 set p 1 foreach prime $primes { if {$current % $prime} {} else { set p 0 break } } if {$p} { return [lindex [lappend primes $current] [incr index]] } } } proc factors {num} { restart set factors [dict create] for {set i [get_next_prime]} {$i <= $num} {} { if {$num % $i == 0} { dict incr factors $i set num [expr {$num / $i}] continue } elseif {$i*$i > $num} { dict incr factors $num break } else { set i [get_next_prime] } } return $factors } proc factors.rendered {num} { set factorDict [factors $num] if {[dict size $factorDict] == 0} { return 1 } dict for {factor times} $factorDict { lappend v {*}[lrepeat $times $factor] } return [join $v "*"] } }
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() } }
Write a version of this C function in Rust with identical behavior.
#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; }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Change the programming language of this snippet from Go to Rust without modifying what it does.
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() } }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Transform the following Rust implementation into Python, maintaining the same output and logic.
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![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())
Convert the following code from Rust to VB, ensuring the logic remains intact.
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![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
Write the same code in Rust as shown below in C++.
#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" ); }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Port the provided C# code into Rust while preserving the original functionality.
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; } } }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Ensure the translated Rust code behaves exactly like the original Java snippet.
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; } }
use std::env; fn main() { let args: Vec<_> = env::args().collect(); let n = if args.len() > 1 { args[1].parse().expect("Not a valid number to count to") } else { 20 }; count_in_factors_to(n); } fn count_in_factors_to(n: u64) { println!("1"); let mut primes = vec![]; for i in 2..=n { let fs = factors(&primes, i); if fs.len() <= 1 { primes.push(i); println!("{}", i); } else { println!("{} = {}", i, fs.iter().map(|f| f.to_string()).collect::<Vec<String>>().join(" x ")); } } } fn factors(primes: &[u64], mut n: u64) -> Vec<u64> { let mut result = Vec::new(); for p in primes { while n % p == 0 { result.push(*p); n /= p; } if n == 1 { return result; } } vec![n] }
Convert this Ada block to C#, preserving its control flow and logic.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
public class FIFO<T> { class Node { public T Item { get; set; } public Node Next { get; set; } } Node first = null; Node last = null; public void push(T item) { if (empty()) { first = new Node() { Item = item, Next = null }; last = first; } else { last.Next = new Node() { Item = item, Next = null }; last = last.Next; } } public T pop() { if (first == null) throw new System.Exception("No elements"); if (last == first) last = null; T temp = first.Item; first = first.Next; return temp; } public bool empty() { return first == null; } }
Rewrite this program in C while keeping its functionality equivalent to the Ada version.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empty(queue q) { return q->tail == q->head; } void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; if (q->tail == q->alloc) { q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, sizeof(DATA) * (q->alloc - q->head)); q->head += q->alloc; } else q->tail = q->alloc; q->alloc *= 2; } } int dequeue(queue q, DATA *n) { if (q->head == q->tail) return 0; *n = q->buf[q->head++]; if (q->head >= q->alloc) { q->head = 0; if (q->alloc >= 512 && q->tail < q->alloc / 2) q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); } return 1; }
Can you help me rewrite this code in C++ instead of Ada, keeping it the same logically?
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
Rewrite this program in Go while keeping its functionality equivalent to the Ada version.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
package queue type Queue struct { b []string head, tail int } func (q *Queue) Push(x string) { switch { case q.tail < 0: next := len(q.b) bigger := make([]string, 2*next) copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head]) bigger[next] = x q.b, q.head, q.tail = bigger, 0, next+1 case len(q.b) == 0: q.b, q.head, q.tail = make([]string, 4), 0 ,1 q.b[0] = x default: q.b[q.tail] = x q.tail++ if q.tail == len(q.b) { q.tail = 0 } if q.tail == q.head { q.tail = -1 } } } func (q *Queue) Pop() (string, bool) { if q.head == q.tail { return "", false } r := q.b[q.head] if q.tail == -1 { q.tail = q.head } q.head++ if q.head == len(q.b) { q.head = 0 } return r, true } func (q *Queue) Empty() bool { return q.head == q.tail }
Rewrite this program in Java while keeping its functionality equivalent to the Ada version.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
public class Queue<E>{ Node<E> head = null, tail = null; static class Node<E>{ E value; Node<E> next; Node(E value, Node<E> next){ this.value= value; this.next= next; } } public Queue(){ } public void enqueue(E value){ Node<E> newNode= new Node<E>(value, null); if(empty()){ head= newNode; }else{ tail.next = newNode; } tail= newNode; } public E dequeue() throws java.util.NoSuchElementException{ if(empty()){ throw new java.util.NoSuchElementException("No more elements."); } E retVal= head.value; head= head.next; return retVal; } public boolean empty(){ return head == null; } }
Translate the given Ada code snippet into Python without altering its behavior.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
class FIFO(object): def __init__(self, *args): self.contents = list(args) def __call__(self): return self.pop() def __len__(self): return len(self.contents) def pop(self): return self.contents.pop(0) def push(self, item): self.contents.append(item) def extend(self,*itemlist): self.contents += itemlist def empty(self): return bool(self.contents) def __iter__(self): return self def next(self): if self.empty(): raise StopIteration return self.pop() if __name__ == "__main__": f = FIFO() f.push(3) f.push(2) f.push(1) while not f.empty(): print f.pop(), f = FIFO(3,2,1) while not f.empty(): print f(), f = FIFO(3,2,1) while f: print f(), f = FIFO(3,2,1) for i in f: print i,
Produce a functionally identical VB code for the snippet given in Ada.
generic type Element_Type is private; package Fifo is type Fifo_Type is private; procedure Push(List : in out Fifo_Type; Item : in Element_Type); procedure Pop(List : in out Fifo_Type; Item : out Element_Type); function Is_Empty(List : Fifo_Type) return Boolean; Empty_Error : exception; private type Fifo_Element; type Fifo_Ptr is access Fifo_Element; type Fifo_Type is record Head : Fifo_Ptr := null; Tail : Fifo_Ptr := null; end record; type Fifo_Element is record Value : Element_Type; Next : Fifo_Ptr := null; end record; end Fifo;
Public queue As New Collection Private Sub push(what As Variant) queue.Add what End Sub Private Function pop() As Variant If queue.Count > 0 Then what = queue(1) queue.Remove 1 Else what = CVErr(461) End If pop = what End Function Private Function empty_() empty_ = queue.Count = 0 End Function
Keep all operations the same but rewrite the snippet in C.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empty(queue q) { return q->tail == q->head; } void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; if (q->tail == q->alloc) { q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, sizeof(DATA) * (q->alloc - q->head)); q->head += q->alloc; } else q->tail = q->alloc; q->alloc *= 2; } } int dequeue(queue q, DATA *n) { if (q->head == q->tail) return 0; *n = q->buf[q->head++]; if (q->head >= q->alloc) { q->head = 0; if (q->alloc >= 512 && q->tail < q->alloc / 2) q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); } return 1; }
Port the provided Arturo code into C# while preserving the original functionality.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
public class FIFO<T> { class Node { public T Item { get; set; } public Node Next { get; set; } } Node first = null; Node last = null; public void push(T item) { if (empty()) { first = new Node() { Item = item, Next = null }; last = first; } else { last.Next = new Node() { Item = item, Next = null }; last = last.Next; } } public T pop() { if (first == null) throw new System.Exception("No elements"); if (last == first) last = null; T temp = first.Item; first = first.Next; return temp; } public bool empty() { return first == null; } }
Produce a language-to-language conversion: from Arturo to C++, same semantics.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
Produce a language-to-language conversion: from Arturo to Java, same semantics.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
public class Queue<E>{ Node<E> head = null, tail = null; static class Node<E>{ E value; Node<E> next; Node(E value, Node<E> next){ this.value= value; this.next= next; } } public Queue(){ } public void enqueue(E value){ Node<E> newNode= new Node<E>(value, null); if(empty()){ head= newNode; }else{ tail.next = newNode; } tail= newNode; } public E dequeue() throws java.util.NoSuchElementException{ if(empty()){ throw new java.util.NoSuchElementException("No more elements."); } E retVal= head.value; head= head.next; return retVal; } public boolean empty(){ return head == null; } }
Rewrite this program in Python while keeping its functionality equivalent to the Arturo version.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
class FIFO(object): def __init__(self, *args): self.contents = list(args) def __call__(self): return self.pop() def __len__(self): return len(self.contents) def pop(self): return self.contents.pop(0) def push(self, item): self.contents.append(item) def extend(self,*itemlist): self.contents += itemlist def empty(self): return bool(self.contents) def __iter__(self): return self def next(self): if self.empty(): raise StopIteration return self.pop() if __name__ == "__main__": f = FIFO() f.push(3) f.push(2) f.push(1) while not f.empty(): print f.pop(), f = FIFO(3,2,1) while not f.empty(): print f(), f = FIFO(3,2,1) while f: print f(), f = FIFO(3,2,1) for i in f: print i,
Translate this program into VB but keep the logic exactly as in Arturo.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
Public queue As New Collection Private Sub push(what As Variant) queue.Add what End Sub Private Function pop() As Variant If queue.Count > 0 Then what = queue(1) queue.Remove 1 Else what = CVErr(461) End If pop = what End Function Private Function empty_() empty_ = queue.Count = 0 End Function
Transform the following Arturo implementation into Go, maintaining the same output and logic.
rebol [ Title: "FIFO" URL: http://rosettacode.org/wiki/FIFO ] fifo: make object! [ queue: copy [] push: func [x][append queue x] pop: func [/local x][ if empty [return none] x: first queue remove queue x] empty: does [empty? queue] ] q: make fifo [] q/push 'a q/push 2 q/push USD$12.34 q/push [Athos Porthos Aramis] q/push [[Huey Dewey Lewey]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] while [not q/empty][print [" " q/pop]] print rejoin ["Queue is " either q/empty [""]["not "] "empty."] print ["Trying to pop an empty queue yields:" q/pop]
package queue type Queue struct { b []string head, tail int } func (q *Queue) Push(x string) { switch { case q.tail < 0: next := len(q.b) bigger := make([]string, 2*next) copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head]) bigger[next] = x q.b, q.head, q.tail = bigger, 0, next+1 case len(q.b) == 0: q.b, q.head, q.tail = make([]string, 4), 0 ,1 q.b[0] = x default: q.b[q.tail] = x q.tail++ if q.tail == len(q.b) { q.tail = 0 } if q.tail == q.head { q.tail = -1 } } } func (q *Queue) Pop() (string, bool) { if q.head == q.tail { return "", false } r := q.b[q.head] if q.tail == -1 { q.tail = q.head } q.head++ if q.head == len(q.b) { q.head = 0 } return r, true } func (q *Queue) Empty() bool { return q.head == q.tail }
Generate an equivalent C version of this AutoHotKey code.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empty(queue q) { return q->tail == q->head; } void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; if (q->tail == q->alloc) { q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, sizeof(DATA) * (q->alloc - q->head)); q->head += q->alloc; } else q->tail = q->alloc; q->alloc *= 2; } } int dequeue(queue q, DATA *n) { if (q->head == q->tail) return 0; *n = q->buf[q->head++]; if (q->head >= q->alloc) { q->head = 0; if (q->alloc >= 512 && q->tail < q->alloc / 2) q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); } return 1; }
Write the same algorithm in C# as shown in this AutoHotKey implementation.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
public class FIFO<T> { class Node { public T Item { get; set; } public Node Next { get; set; } } Node first = null; Node last = null; public void push(T item) { if (empty()) { first = new Node() { Item = item, Next = null }; last = first; } else { last.Next = new Node() { Item = item, Next = null }; last = last.Next; } } public T pop() { if (first == null) throw new System.Exception("No elements"); if (last == first) last = null; T temp = first.Item; first = first.Next; return temp; } public bool empty() { return first == null; } }
Write the same code in C++ as shown below in AutoHotKey.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
Port the provided AutoHotKey code into Java while preserving the original functionality.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
public class Queue<E>{ Node<E> head = null, tail = null; static class Node<E>{ E value; Node<E> next; Node(E value, Node<E> next){ this.value= value; this.next= next; } } public Queue(){ } public void enqueue(E value){ Node<E> newNode= new Node<E>(value, null); if(empty()){ head= newNode; }else{ tail.next = newNode; } tail= newNode; } public E dequeue() throws java.util.NoSuchElementException{ if(empty()){ throw new java.util.NoSuchElementException("No more elements."); } E retVal= head.value; head= head.next; return retVal; } public boolean empty(){ return head == null; } }
Maintain the same structure and functionality when rewriting this code in Python.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
class FIFO(object): def __init__(self, *args): self.contents = list(args) def __call__(self): return self.pop() def __len__(self): return len(self.contents) def pop(self): return self.contents.pop(0) def push(self, item): self.contents.append(item) def extend(self,*itemlist): self.contents += itemlist def empty(self): return bool(self.contents) def __iter__(self): return self def next(self): if self.empty(): raise StopIteration return self.pop() if __name__ == "__main__": f = FIFO() f.push(3) f.push(2) f.push(1) while not f.empty(): print f.pop(), f = FIFO(3,2,1) while not f.empty(): print f(), f = FIFO(3,2,1) while f: print f(), f = FIFO(3,2,1) for i in f: print i,
Port the provided AutoHotKey code into VB while preserving the original functionality.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
Public queue As New Collection Private Sub push(what As Variant) queue.Add what End Sub Private Function pop() As Variant If queue.Count > 0 Then what = queue(1) queue.Remove 1 Else what = CVErr(461) End If pop = what End Function Private Function empty_() empty_ = queue.Count = 0 End Function
Rewrite the snippet below in Go so it works the same as the original AutoHotKey code.
push("qu", 2), push("qu", 44), push("qu", "xyz")  MsgBox % "Len = " len("qu")  While !empty("qu")   MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % pop("qu")   MsgBox Error = %ErrorLevel%  MsgBox % "Len = " len("qu")  push(queue,_) {   Global %queue% .= %queue% = "" ? _ : "|" _ } pop(queue) {   Global RegExMatch(%queue%, "([^\|]*)\|?(.*)", _) Return _1, ErrorLevel := -(%queue%=""), %queue% := _2 } empty(queue) {   Global Return %queue% = "" } len(queue) {   Global StringReplace %queue%, %queue%, |, |, UseErrorLevel Return %queue% = "" ? 0 : ErrorLevel+1 }
package queue type Queue struct { b []string head, tail int } func (q *Queue) Push(x string) { switch { case q.tail < 0: next := len(q.b) bigger := make([]string, 2*next) copy(bigger[copy(bigger, q.b[q.head:]):], q.b[:q.head]) bigger[next] = x q.b, q.head, q.tail = bigger, 0, next+1 case len(q.b) == 0: q.b, q.head, q.tail = make([]string, 4), 0 ,1 q.b[0] = x default: q.b[q.tail] = x q.tail++ if q.tail == len(q.b) { q.tail = 0 } if q.tail == q.head { q.tail = -1 } } } func (q *Queue) Pop() (string, bool) { if q.head == q.tail { return "", false } r := q.b[q.head] if q.tail == -1 { q.tail = q.head } q.head++ if q.head == len(q.b) { q.head = 0 } return r, true } func (q *Queue) Empty() bool { return q.head == q.tail }
Generate an equivalent C version of this AWK code.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef int DATA; typedef struct { DATA *buf; size_t head, tail, alloc; } queue_t, *queue; queue q_new() { queue q = malloc(sizeof(queue_t)); q->buf = malloc(sizeof(DATA) * (q->alloc = 4)); q->head = q->tail = 0; return q; } int empty(queue q) { return q->tail == q->head; } void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; if (q->tail == q->alloc) { q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, sizeof(DATA) * (q->alloc - q->head)); q->head += q->alloc; } else q->tail = q->alloc; q->alloc *= 2; } } int dequeue(queue q, DATA *n) { if (q->head == q->tail) return 0; *n = q->buf[q->head++]; if (q->head >= q->alloc) { q->head = 0; if (q->alloc >= 512 && q->tail < q->alloc / 2) q->buf = realloc(q->buf, sizeof(DATA) * (q->alloc/=2)); } return 1; }
Keep all operations the same but rewrite the snippet in C#.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
public class FIFO<T> { class Node { public T Item { get; set; } public Node Next { get; set; } } Node first = null; Node last = null; public void push(T item) { if (empty()) { first = new Node() { Item = item, Next = null }; last = first; } else { last.Next = new Node() { Item = item, Next = null }; last = last.Next; } } public T pop() { if (first == null) throw new System.Exception("No elements"); if (last == first) last = null; T temp = first.Item; first = first.Next; return temp; } public bool empty() { return first == null; } }
Transform the following AWK implementation into C++, maintaining the same output and logic.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
namespace rosettacode { template<typename T> class queue { public: queue(); ~queue(); void push(T const& t); T pop(); bool empty(); private: void drop(); struct node; node* head; node* tail; }; template<typename T> struct queue<T>::node { T data; node* next; node(T const& t): data(t), next(0) {} }; template<typename T> queue<T>::queue(): head(0) { } template<typename T> inline void queue<T>::drop() { node* n = head; head = head->next; delete n; } template<typename T> queue<T>::~queue() { while (!empty()) drop(); } template<typename T> void queue<T>::push(T const& t) { node*& next = head? tail->next : head; next = new node(t); tail = next; } template<typename T> T queue<T>::pop() { T tmp = head->data; drop(); return tmp; } template<typename T> bool queue<T>::empty() { return head == 0; } }
Write the same algorithm in Java as shown in this AWK implementation.
BEGIN { delete q print "empty? " emptyP() print "push " push("a") print "push " push("b") print "empty? " emptyP() print "pop " pop() print "pop " pop() print "empty? " emptyP() print "pop " pop() } function push(n) { q[length(q)+1] = n return n } function pop() { if (emptyP()) { print "Popping from empty queue." exit } r = q[length(q)] delete q[length(q)] return r } function emptyP() { return length(q) == 0 }
public class Queue<E>{ Node<E> head = null, tail = null; static class Node<E>{ E value; Node<E> next; Node(E value, Node<E> next){ this.value= value; this.next= next; } } public Queue(){ } public void enqueue(E value){ Node<E> newNode= new Node<E>(value, null); if(empty()){ head= newNode; }else{ tail.next = newNode; } tail= newNode; } public E dequeue() throws java.util.NoSuchElementException{ if(empty()){ throw new java.util.NoSuchElementException("No more elements."); } E retVal= head.value; head= head.next; return retVal; } public boolean empty(){ return head == null; } }