Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate the given Common_Lisp code snippet into Go without altering its behavior. | (defun factorial (n)
(if (< n 2) 1 (* n (factorial (1- n)))) )
(defun primep (n)
"Primality test using Wilson's Theorem"
(unless (zerop n)
(zerop (mod (1+ (factorial (1- n))) n)) ))
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Rewrite the snippet below in C so it works the same as the original D code. | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Can you help me rewrite this code in C++ instead of D, keeping it the same logically? | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Generate an equivalent Java version of this D code. | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Transform the following D implementation into Python, maintaining the same output and logic. | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Transform the following D implementation into Go, maintaining the same output and logic. | import std.bigint;
import std.stdio;
BigInt fact(long n) {
BigInt f = 1;
for (int i = 2; i <= n; i++) {
f *= i;
}
return f;
}
bool isPrime(long p) {
if (p <= 1) {
return false;
}
return (fact(p - 1) + 1) % p == 0;
}
void main() {
writeln("Primes less than 100 testing by Wilson's Theorem");
foreach (i; 0 .. 101) {
if (isPrime(i)) {
write(i, ' ');
}
}
writeln;
}
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Generate a C translation of this Erlang snippet without changing its computational steps. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Write a version of this Erlang function in C# with identical behavior. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Write the same code in C++ as shown below in Erlang. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Write the same code in Java as shown below in Erlang. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Change the programming language of this snippet from Erlang to Python without modifying what it does. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Convert this Erlang snippet to Go and keep its semantics consistent. | #! /usr/bin/escript
isprime(N) when N < 2 -> false;
isprime(N) when N band 1 =:= 0 -> N =:= 2;
isprime(N) -> fac_mod(N - 1, N) =:= N - 1.
fac_mod(N, M) -> fac_mod(N, M, 1).
fac_mod(1, _, A) -> A;
fac_mod(N, M, A) -> fac_mod(N - 1, M, A*N rem M).
main(_) ->
io:format("The first few primes (via Wilson's theorem) are: ~n~p~n",
[[K || K <- lists:seq(1, 128), isprime(K)]]).
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Generate an equivalent C version of this F# code. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Transform the following F# implementation into C#, maintaining the same output and logic. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Generate an equivalent C++ version of this F# code. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Translate the given F# code snippet into Java without altering its behavior. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Preserve the algorithm and functionality while converting the code from F# to Python. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Translate the given F# code snippet into Go without altering its behavior. |
let wP(n,g)=(n+1I)%g=0I
let fN=Seq.unfold(fun(n,g)->Some((n,g),((n*g),(g+1I))))(1I,2I)|>Seq.filter wP
fN|>Seq.take 120|>Seq.iter(fun(_,n)->printf "%A " n);printfn "\n"
fN|>Seq.skip 999|>Seq.take 15|>Seq.iter(fun(_,n)->printf "%A " n);printfn ""
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Keep all operations the same but rewrite the snippet in C. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Convert this Factor block to C#, preserving its control flow and logic. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Maintain the same structure and functionality when rewriting this code in C++. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Produce a functionally identical Java code for the snippet given in Factor. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Translate this program into Python but keep the logic exactly as in Factor. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Transform the following Factor implementation into Go, maintaining the same output and logic. | USING: formatting grouping io kernel lists lists.lazy math
math.factorials math.functions prettyprint sequences ;
: wilson ( n -- ? ) [ 1 - factorial 1 + ] [ divisor? ] bi ;
: prime? ( n -- ? ) dup 2 < [ drop f ] [ wilson ] if ;
: primes ( -- list ) 1 lfrom [ prime? ] lfilter ;
"n prime?\n--- -----" print
{ 2 3 9 15 29 37 47 57 67 77 87 97 237 409 659 }
[ dup prime? "%-3d %u\n" printf ] each nl
"First 120 primes via Wilson's theorem:" print
120 primes ltake list>array 20 group simple-table. nl
"1000th through 1015th primes:" print
16 primes 999 [ cdr ] times ltake list>array
[ pprint bl ] each nl
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Produce a functionally identical C code for the snippet given in Forth. | : fac-mod
>r 1 swap
begin dup 0> while
dup rot * r@ mod swap 1-
repeat drop rdrop ;
: ?prime
dup 1- tuck swap fac-mod = ;
: .primes
cr 2 ?do i ?prime if i . then loop ;
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Port the following code from Forth to C# with equivalent syntax and logic. | : fac-mod
>r 1 swap
begin dup 0> while
dup rot * r@ mod swap 1-
repeat drop rdrop ;
: ?prime
dup 1- tuck swap fac-mod = ;
: .primes
cr 2 ?do i ?prime if i . then loop ;
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Can you help me rewrite this code in C++ instead of Forth, keeping it the same logically? | : fac-mod
>r 1 swap
begin dup 0> while
dup rot * r@ mod swap 1-
repeat drop rdrop ;
: ?prime
dup 1- tuck swap fac-mod = ;
: .primes
cr 2 ?do i ?prime if i . then loop ;
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Produce a functionally identical Java code for the snippet given in Forth. | : fac-mod
>r 1 swap
begin dup 0> while
dup rot * r@ mod swap 1-
repeat drop rdrop ;
: ?prime
dup 1- tuck swap fac-mod = ;
: .primes
cr 2 ?do i ?prime if i . then loop ;
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Translate the given Forth code snippet into Python without altering its behavior. | : fac-mod
>r 1 swap
begin dup 0> while
dup rot * r@ mod swap 1-
repeat drop rdrop ;
: ?prime
dup 1- tuck swap fac-mod = ;
: .primes
cr 2 ?do i ?prime if i . then loop ;
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Translate the given Haskell code snippet into C without altering its behavior. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Haskell to C#. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Generate an equivalent C++ version of this Haskell code. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Preserve the algorithm and functionality while converting the code from Haskell to Java. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Generate a Python translation of this Haskell snippet without changing its computational steps. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Produce a functionally identical Go code for the snippet given in Haskell. | import qualified Data.Text as T
import Data.List
main = do
putStrLn $ showTable True ' ' '-' ' ' $ ["p","isPrime"]:map (\p -> [show p, show $ isPrime p]) numbers
putStrLn $ "The first 120 prime numbers are:"
putStrLn $ see 20 $ take 120 primes
putStrLn "The 1,000th to 1,015th prime numbers are:"
putStrLn $ see 16.take 16 $ drop 999 primes
numbers = [2,3,9,15,29,37,47,57,67,77,87,97,237,409,659]
primes = [p | p <- 2:[3,5..], isPrime p]
isPrime :: Integer -> Bool
isPrime p = if p < 2 then False else 0 == mod (succ $ product [1..pred p]) p
bagOf :: Int -> [a] -> [[a]]
bagOf _ [] = []
bagOf n xs = let (us,vs) = splitAt n xs in us : bagOf n vs
see :: Show a => Int -> [a] -> String
see n = unlines.map unwords.bagOf n.map (T.unpack.T.justifyRight 3 ' '.T.pack.show)
showTable::Bool -> Char -> Char -> Char -> [[String]] -> String
showTable _ _ _ _ [] = []
showTable header ver hor sep contents = unlines $ hr:(if header then z:hr:zs else intersperse hr zss) ++ [hr]
where
vss = map (map length) $ contents
ms = map maximum $ transpose vss ::[Int]
hr = concatMap (\ n -> sep : replicate n hor) ms ++ [sep]
top = replicate (length hr) hor
bss = map (\ps -> map (flip replicate ' ') $ zipWith (-) ms ps) $ vss
zss@(z:zs) = zipWith (\us bs -> (concat $ zipWith (\x y -> (ver:x) ++ y) us bs) ++ [ver]) contents bss
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Preserve the algorithm and functionality while converting the code from J to C. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Transform the following J implementation into C#, maintaining the same output and logic. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Generate a C++ translation of this J snippet without changing its computational steps. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Convert the following code from J to Java, ensuring the logic remains intact. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Translate this program into Python but keep the logic exactly as in J. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Generate a Go translation of this J snippet without changing its computational steps. | wilson=: 0 = (| !&.:<:)
(#~ wilson) x: 2 + i. 30
2 3 5 7 11 13 17 19 23 29 31
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Preserve the algorithm and functionality while converting the code from Julia to C. | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Write the same algorithm in C# as shown in this Julia implementation. | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Please provide an equivalent version of this Julia code in C++. | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Ensure the translated Java code behaves exactly like the original Julia snippet. | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Can you help me rewrite this code in Python instead of Julia, keeping it the same logically? | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Convert this Julia block to Go, preserving its control flow and logic. | iswilsonprime(p) = (p < 2 || (p > 2 && iseven(p))) ? false : foldr((x, y) -> (x * y) % p, 1:p - 1) == p - 1
wilsonprimesbetween(n, m) = [i for i in n:m if iswilsonprime(i)]
println("First 120 Wilson primes: ", wilsonprimesbetween(1, 1000)[1:120])
println("\nThe first 40 Wilson primes above 7900 are: ", wilsonprimesbetween(7900, 9000)[1:40])
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Produce a language-to-language conversion: from Lua to C, same semantics. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Lua version. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Port the provided Lua code into C++ while preserving the original functionality. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Write a version of this Lua function in Java with identical behavior. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Write the same code in Go as shown below in Lua. |
function isWilsonPrime( n )
local fmodp = 1
for i = 2, n - 1 do
fmodp = fmodp * i
fmodp = fmodp % n
end
return fmodp == n - 1
end
for n = -1, 100 do
if isWilsonPrime( n ) then
io.write( " " .. n )
end
end
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Can you help me rewrite this code in C instead of Mathematica, keeping it the same logically? | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Write the same algorithm in C# as shown in this Mathematica implementation. | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Mathematica version. | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Convert this Mathematica block to Java, preserving its control flow and logic. | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Port the provided Mathematica code into Python while preserving the original functionality. | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Convert the following code from Mathematica to Go, ensuring the logic remains intact. | ClearAll[WilsonPrimeQ]
WilsonPrimeQ[1] = False;
WilsonPrimeQ[p_Integer] := Divisible[(p - 1)! + 1, p]
Select[Range[100], WilsonPrimeQ]
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Write the same code in C as shown below in Nim. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Write the same code in C# as shown below in Nim. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Nim version. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Produce a functionally identical Java code for the snippet given in Nim. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Transform the following Nim implementation into Python, maintaining the same output and logic. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Port the following code from Nim to Go with equivalent syntax and logic. | import strutils, sugar
proc facmod(n, m: int): int =
result = 1
for k in 2..n:
result = (result * k) mod m
func isPrime(n: int): bool = (facmod(n - 1, n) + 1) mod n == 0
let primes = collect(newSeq):
for n in 2..100:
if n.isPrime: n
echo "Prime numbers between 2 and 100:"
echo primes.join(" ")
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Convert this Pascal snippet to C and keep its semantics consistent. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Generate a C# translation of this Pascal snippet without changing its computational steps. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Pascal version. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Convert this Pascal snippet to Java and keep its semantics consistent. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Change the programming language of this snippet from Pascal to Python without modifying what it does. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Convert this Pascal block to Go, preserving its control flow and logic. | program PrimesByWilson;
uses SysUtils;
function WilsonFullCalc( n : longword) : boolean;
var
f, m : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
for m := 2 to n - 1 do begin
f := (uint64(f) * uint64(m)) mod n;
end;
result := (f = n - 1);
end;
function WilsonShortCut( n : longword) : boolean;
var
f, g, h, m, m2inc, r : longword;
begin
if n < 2 then begin
result := false; exit;
end;
f := 1;
m := 1;
m2inc := 3;
r := n - 1;
while r >= m2inc do begin
inc(m);
f := (uint64(f) * uint64(m)) mod n;
dec( r, m2inc);
inc( m2inc, 2);
end;
h := n;
while f <> 0 do begin
g := h mod f;
h := f;
f := g;
end;
result := (h = 1);
end;
type TPrimalityTest = function( n : longword) : boolean;
procedure ShowPrimes( isPrime : TPrimalityTest;
minValue, maxValue : longword);
var
n : longword;
begin
WriteLn( 'Primes in ', minValue, '..', maxValue);
for n := minValue to maxValue do
if isPrime(n) then Write(' ', n);
WriteLn;
end;
begin
WriteLn( 'By full calculation:');
ShowPrimes( @WilsonFullCalc, 1, 100);
ShowPrimes( @WilsonFullCalc, 1000, 1100);
WriteLn; WriteLn( 'Using the short cut:');
ShowPrimes( @WilsonShortCut, 1, 100);
ShowPrimes( @WilsonShortCut, 1000, 1100);
ShowPrimes( @WilsonShortCut, 4294967195, 4294967295 );
end.
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Ensure the translated C code behaves exactly like the original Perl snippet. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Perl to C#. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Translate this program into C++ but keep the logic exactly as in Perl. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Produce a functionally identical Java code for the snippet given in Perl. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Write the same algorithm in Python as shown in this Perl implementation. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Generate a Go translation of this Perl snippet without changing its computational steps. | use strict;
use warnings;
use feature 'say';
use ntheory qw(factorial);
my($ends_in_7, $ends_in_3);
sub is_wilson_prime {
my($n) = @_;
$n > 1 or return 0;
(factorial($n-1) % $n) == ($n-1) ? 1 : 0;
}
for (0..50) {
my $m = 3 + 10 * $_;
$ends_in_3 .= "$m " if is_wilson_prime($m);
my $n = 7 + 10 * $_;
$ends_in_7 .= "$n " if is_wilson_prime($n);
}
say $ends_in_3;
say $ends_in_7;
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Translate this program into C but keep the logic exactly as in REXX. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Convert the following code from REXX to C#, ensuring the logic remains intact. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Preserve the algorithm and functionality while converting the code from REXX to C++. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Change the following REXX code into Java without altering its purpose. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Generate an equivalent Python version of this REXX code. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Convert this REXX block to Go, preserving its control flow and logic. |
parse arg LO zz
if LO=='' | LO=="," then LO= 120
if zz ='' | zz ="," then zz=2 3 9 15 29 37 47 57 67 77 87 97 237 409 659
sw= linesize() - 1; if sw<1 then sw= 79
digs = digits()
#= 0
!.= 1
$=
do p=1 until #=LO; oDigs= digs
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
if \? then iterate
#= # + 1; $= $ p
end
call show 'The first ' LO " prime numbers are:"
w= max( length(LO), length(word(reverse(zz),1)))
@is.0= " isn't"; @is.1= 'is'
say
do z=1 for words(zz); oDigs= digs
p= word(zz, z)
?= isPrimeW(p)
if digs>Odigs then numeric digits digs
say right(p, max(w,length(p) ) ) @is.? "prime."
end
exit
isPrimeW: procedure expose !. digs; parse arg x '' -1 last; != 1; xm= x - 1
if x<2 then return 0
if x==2 | x==5 then return 1
if last//2==0 | last==5 then return 0
if !.xm\==1 then != !.xm
else do; if xm>!.0 then do; base= !.0+1; _= !.0; != !._; end
else base= 2
do j=!.0+1 to xm; != ! * j
if pos(., !)\==0 then do; parse var ! 'E' expon
numeric digits expon +99
digs = digits()
end
end
if xm<999 then do; !.xm=!; !.0=xm; end
end
if (!+1)//x==0 then return 1
return 0
show: parse arg header,oo; say header
w= length( word($, LO) )
do k=1 for LO; _= right( word($, k), w)
if length(oo _)>sw then do; say substr(oo,2); oo=; end
oo= oo _
end
if oo\='' then say substr(oo, 2); return
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Produce a functionally identical C code for the snippet given in Ruby. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Convert this Ruby block to C#, preserving its control flow and logic. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Ruby version. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Write the same code in Java as shown below in Ruby. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Ruby version. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Preserve the algorithm and functionality while converting the code from Ruby to Go. | def w_prime?(i)
return false if i < 2
((1..i-1).inject(&:*) + 1) % i == 0
end
p (1..100).select{|n| w_prime?(n) }
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Produce a functionally identical C code for the snippet given in Swift. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
|
Write the same algorithm in C# as shown in this Swift implementation. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
|
Keep all operations the same but rewrite the snippet in C++. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
|
Generate an equivalent Java version of this Swift code. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| from math import factorial
def is_wprime(n):
return n == 2 or (
n > 1
and n % 2 != 0
and (factorial(n - 1) + 1) % n == 0
)
if __name__ == '__main__':
c = int(input('Enter upper limit: '))
print(f'Primes under {c}:')
print([n for n in range(c) if is_wprime(n)])
|
Transform the following Swift implementation into Go, maintaining the same output and logic. | import BigInt
func factorial<T: BinaryInteger>(_ n: T) -> T {
guard n != 0 else {
return 1
}
return stride(from: n, to: 0, by: -1).reduce(1, *)
}
func isWilsonPrime<T: BinaryInteger>(_ n: T) -> Bool {
guard n >= 2 else {
return false
}
return (factorial(n - 1) + 1) % n == 0
}
print((1...100).map({ BigInt($0) }).filter(isWilsonPrime))
| package main
import (
"fmt"
"math/big"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
prev = big.NewInt(factorial(20))
)
func factorial(n int64) int64 {
res := int64(1)
for k := n; k > 1; k-- {
res *= k
}
return res
}
func wilson(n int64, memo bool) bool {
if n <= 1 || (n%2 == 0 && n != 2) {
return false
}
if n <= 21 {
return (factorial(n-1)+1)%n == 0
}
b := big.NewInt(n)
r := big.NewInt(0)
z := big.NewInt(0)
if !memo {
z.MulRange(2, n-1)
} else {
prev.Mul(prev, r.MulRange(n-2, n-1))
z.Set(prev)
}
z.Add(z, one)
return r.Rem(z, b).Cmp(zero) == 0
}
func main() {
numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}
fmt.Println(" n prime")
fmt.Println("--- -----")
for _, n := range numbers {
fmt.Printf("%3d %t\n", n, wilson(n, false))
}
fmt.Println("\nThe first 120 prime numbers are:")
for i, count := int64(2), 0; count < 1015; i += 2 {
if wilson(i, true) {
count++
if count <= 120 {
fmt.Printf("%3d ", i)
if count%20 == 0 {
fmt.Println()
}
} else if count >= 1000 {
if count == 1000 {
fmt.Println("\nThe 1,000th to 1,015th prime numbers are:")
}
fmt.Printf("%4d ", i)
}
}
if i == 2 {
i--
}
}
fmt.Println()
}
|
Produce a functionally identical Rust code for the snippet given in C. | #include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
uint64_t factorial(uint64_t n) {
uint64_t product = 1;
if (n < 2) {
return 1;
}
for (; n > 0; n--) {
uint64_t prev = product;
product *= n;
if (product < prev) {
fprintf(stderr, "Overflowed\n");
return product;
}
}
return product;
}
bool isPrime(uint64_t n) {
uint64_t large = factorial(n - 1) + 1;
return (large % n) == 0;
}
int main() {
uint64_t n;
for (n = 2; n < 22; n++) {
printf("Is %llu prime: %d\n", n, isPrime(n));
}
return 0;
}
| fn factorial_mod(mut n: u32, p: u32) -> u32 {
let mut f = 1;
while n != 0 && f != 0 {
f = (f * n) % p;
n -= 1;
}
f
}
fn is_prime(p: u32) -> bool {
p > 1 && factorial_mod(p - 1, p) == p - 1
}
fn main() {
println!(" n | prime?\n------------");
for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] {
println!("{:>3} | {}", p, is_prime(p));
}
println!("\nFirst 120 primes by Wilson's theorem:");
let mut n = 0;
let mut p = 1;
while n < 120 {
if is_prime(p) {
n += 1;
print!("{:>3}{}", p, if n % 20 == 0 { '\n' } else { ' ' });
}
p += 1;
}
println!("\n1000th through 1015th primes:");
let mut i = 0;
while n < 1015 {
if is_prime(p) {
n += 1;
if n >= 1000 {
i += 1;
print!("{:>3}{}", p, if i % 16 == 0 { '\n' } else { ' ' });
}
}
p += 1;
}
}
|
Change the programming language of this snippet from C++ to Rust without modifying what it does. | #include <iomanip>
#include <iostream>
int factorial_mod(int n, int p) {
int f = 1;
for (; n > 0 && f != 0; --n)
f = (f * n) % p;
return f;
}
bool is_prime(int p) {
return p > 1 && factorial_mod(p - 1, p) == p - 1;
}
int main() {
std::cout << " n | prime?\n------------\n";
std::cout << std::boolalpha;
for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659})
std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n';
std::cout << "\nFirst 120 primes by Wilson's theorem:\n";
int n = 0, p = 1;
for (; n < 120; ++p) {
if (is_prime(p))
std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' ');
}
std::cout << "\n1000th through 1015th primes:\n";
for (int i = 0; n < 1015; ++p) {
if (is_prime(p)) {
if (++n >= 1000)
std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' ');
}
}
}
| fn factorial_mod(mut n: u32, p: u32) -> u32 {
let mut f = 1;
while n != 0 && f != 0 {
f = (f * n) % p;
n -= 1;
}
f
}
fn is_prime(p: u32) -> bool {
p > 1 && factorial_mod(p - 1, p) == p - 1
}
fn main() {
println!(" n | prime?\n------------");
for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] {
println!("{:>3} | {}", p, is_prime(p));
}
println!("\nFirst 120 primes by Wilson's theorem:");
let mut n = 0;
let mut p = 1;
while n < 120 {
if is_prime(p) {
n += 1;
print!("{:>3}{}", p, if n % 20 == 0 { '\n' } else { ' ' });
}
p += 1;
}
println!("\n1000th through 1015th primes:");
let mut i = 0;
while n < 1015 {
if is_prime(p) {
n += 1;
if n >= 1000 {
i += 1;
print!("{:>3}{}", p, if i % 16 == 0 { '\n' } else { ' ' });
}
}
p += 1;
}
}
|
Write the same algorithm in Rust as shown in this C# implementation. | using System;
using System.Linq;
using System.Collections;
using static System.Console;
using System.Collections.Generic;
using BI = System.Numerics.BigInteger;
class Program {
const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st;
static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method",
fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:";
static List<int> lst = new List<int>();
static void Dump(int s, int t, string f) {
foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); }
static string Ord(int x, string fmt = "{0:n0}") {
var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0;
return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); }
static void ShowOne(string title, ref double et) {
WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} ");
WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} ");
WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); }
static BI factorial(int n) { BI res = 1; if (n < 2) return res;
while (n > 0) res *= n--; return res; }
static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; }
static BI[] facts;
static void initFacts(int n) {
facts = new BI[n]; facts[0] = facts[1] = 1;
for (int i = 1, j = 2; j < n; i = j++)
facts[j] = facts[i] * j; }
static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; }
static void Main(string[] args) { st = DateTime.Now;
BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n);
ShowOne(ms1, ref et1);
st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1);
for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) {
lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; }
ShowOne(ms2, ref et2);
WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2);
WriteLine("\n" + ms1 + " stand-alone computation:");
WriteLine("factorial computed for each item");
st = DateTime.Now;
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
WriteLine("factorials precomputed up to highest item");
st = DateTime.Now; initFacts(lst[max - 1]);
for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x);
WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds);
}
}
| fn factorial_mod(mut n: u32, p: u32) -> u32 {
let mut f = 1;
while n != 0 && f != 0 {
f = (f * n) % p;
n -= 1;
}
f
}
fn is_prime(p: u32) -> bool {
p > 1 && factorial_mod(p - 1, p) == p - 1
}
fn main() {
println!(" n | prime?\n------------");
for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] {
println!("{:>3} | {}", p, is_prime(p));
}
println!("\nFirst 120 primes by Wilson's theorem:");
let mut n = 0;
let mut p = 1;
while n < 120 {
if is_prime(p) {
n += 1;
print!("{:>3}{}", p, if n % 20 == 0 { '\n' } else { ' ' });
}
p += 1;
}
println!("\n1000th through 1015th primes:");
let mut i = 0;
while n < 1015 {
if is_prime(p) {
n += 1;
if n >= 1000 {
i += 1;
print!("{:>3}{}", p, if i % 16 == 0 { '\n' } else { ' ' });
}
}
p += 1;
}
}
|
Convert this Java snippet to Rust and keep its semantics consistent. | import java.math.BigInteger;
public class PrimaltyByWilsonsTheorem {
public static void main(String[] args) {
System.out.printf("Primes less than 100 testing by Wilson's Theorem%n");
for ( int i = 0 ; i <= 100 ; i++ ) {
if ( isPrime(i) ) {
System.out.printf("%d ", i);
}
}
}
private static boolean isPrime(long p) {
if ( p <= 1) {
return false;
}
return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0;
}
private static BigInteger fact(long n) {
BigInteger fact = BigInteger.ONE;
for ( int i = 2 ; i <= n ; i++ ) {
fact = fact.multiply(BigInteger.valueOf(i));
}
return fact;
}
}
| fn factorial_mod(mut n: u32, p: u32) -> u32 {
let mut f = 1;
while n != 0 && f != 0 {
f = (f * n) % p;
n -= 1;
}
f
}
fn is_prime(p: u32) -> bool {
p > 1 && factorial_mod(p - 1, p) == p - 1
}
fn main() {
println!(" n | prime?\n------------");
for p in vec![2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659] {
println!("{:>3} | {}", p, is_prime(p));
}
println!("\nFirst 120 primes by Wilson's theorem:");
let mut n = 0;
let mut p = 1;
while n < 120 {
if is_prime(p) {
n += 1;
print!("{:>3}{}", p, if n % 20 == 0 { '\n' } else { ' ' });
}
p += 1;
}
println!("\n1000th through 1015th primes:");
let mut i = 0;
while n < 1015 {
if is_prime(p) {
n += 1;
if n >= 1000 {
i += 1;
print!("{:>3}{}", p, if i % 16 == 0 { '\n' } else { ' ' });
}
}
p += 1;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.