Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Primorial_numbers
note: Prime Numbers

View file

@ -0,0 +1,50 @@
Primorial numbers are those formed by multiplying successive prime numbers.
The primorial number series is:
::*   primorial(0) =         1       (by definition)
::*   primorial(1) =         2       (2)
::*   primorial(2) =         6       (2×3)
::*   primorial(3) =       30       (2×3×5)
::*   primorial(4) =     210       (2×3×5×7)
::*   primorial(5) =   2310       (2×3×5×7×11)
::*   primorial(6) = 30030       (2×3×5×7×11×13)
:;* &nbsp; &nbsp; &nbsp; &nbsp; <big><b>∙ ∙ ∙</b></big>
To express this mathematically, &nbsp; '''primorial<sub><big>''n''</big></sub>''' &nbsp; is &nbsp;
the product of the first &nbsp; <big>''n''</big> &nbsp; (successive) primes:
<big><big><big>
: &nbsp; <math>primorial_n = \prod_{k=1}^n prime_k</math>
</big></big>
:::::: ─── where &nbsp; <big><big><math>prime_k</math></big></big> &nbsp; is the &nbsp; <big><big>''k''<sup>''th''</sup>''</big></big> &nbsp; prime number.
</big>
In some sense, generating primorial numbers is similar to factorials.
As with factorials, primorial numbers get large quickly.
;Task:
* &nbsp; Show the first ten primorial numbers &nbsp; (0 ──► 9, &nbsp; inclusive).
* &nbsp; Show the length of primorial numbers whose index is: &nbsp; 10 &nbsp; 100 &nbsp; 1,000 &nbsp; 10,000 &nbsp; and &nbsp; 100,000.
* &nbsp; Show the length of the one millionth primorial number &nbsp; (optional).
* &nbsp; Use exact integers, not approximations.
By &nbsp; ''length'' &nbsp; (above), it is meant the number of decimal digits in the numbers. <br>
;Related tasks:
* &nbsp; [[Sequence of primorial primes]]
* &nbsp; [[Factorial]]
* &nbsp; [[Fortunate_numbers]]
;See also:
* &nbsp; the MathWorld webpage: &nbsp; [http://mathworld.wolfram.com/Primorial.html primorial]
* &nbsp; the Wikipedia &nbsp; webpage: &nbsp; [[wp:Primorial|primorial]].
* &nbsp; the &nbsp; OEIS &nbsp; webpage: &nbsp; [[oeis:A002110|A002110]].
<br><br>

View file

@ -0,0 +1,28 @@
F get_primes(primes_count)
V limit = 17 * primes_count
V is_prime = [0B] * 2 [+] [1B] * (limit - 1)
L(n) 0 .< Int(limit ^ 0.5 + 1.5)
I is_prime[n]
L(i) (n * n .< limit + 1).step(n)
is_prime[i] = 0B
[Int] primes
L(prime) is_prime
I prime
primes.append(L.index)
I primes.len == primes_count
L.break
R primes
V primes = get_primes(100000)
F primorial(n)
BigInt r = 1
L(i) 0 .< n
r *= :primes[i]
R r
print(First ten primorials: (0.<10).map(n -> primorial(n)))
L(e) 6
V n = 10 ^ e
print(primorial(#.) has #. digits.format(n, String(primorial(n)).len))

View file

@ -0,0 +1,13 @@
primes: [2] ++ select.first: 99999 range.step: 2 3 ∞ => prime?
primorial: function [n][
if 0 = n -> return 1
product take primes n
]
print "First ten primorials:"
loop 0..9 => [print primorial &]
print ""
loop 1..5 'm -> print [
"primorial" 10^m "has" size ~"|primorial 10^m|" "digits"
]

View file

@ -0,0 +1,32 @@
#include <gmpxx.h>
#include <primesieve.hpp>
#include <cstdint>
#include <iomanip>
#include <iostream>
size_t digits(const mpz_class& n) { return n.get_str().length(); }
mpz_class primorial(unsigned int n) {
mpz_class p;
mpz_primorial_ui(p.get_mpz_t(), n);
return p;
}
int main() {
uint64_t index = 0;
primesieve::iterator pi;
std::cout << "First 10 primorial numbers:\n";
for (mpz_class pn = 1; index < 10; ++index) {
unsigned int prime = pi.next_prime();
std::cout << index << ": " << pn << '\n';
pn *= prime;
}
std::cout << "\nLength of primorial number whose index is:\n";
for (uint64_t power = 10; power <= 1000000; power *= 10) {
uint64_t prime = primesieve::nth_prime(power);
std::cout << std::setw(7) << power << ": "
<< digits(primorial(prime)) << '\n';
}
return 0;
}

View file

@ -0,0 +1,35 @@
using System;
class Program {
static int l;
static int[] gp(int n) {
var c = new bool[n]; var r = new int[(int)(1.28 * n)];
l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n);
for (int i = 9; i < n; i += 6) c[i] = true;
for (j = 5, d = 4; j < lim; j += (d = 6 - d)) if (!c[j]) { r[l++] = j;
for (int k = j * j, ki = j << 1; k < n; k += ki) c[k] = true; }
for ( ; j < n; j += (d = 6 - d)) if (!c[j]) r[l++] = j; return r; }
static void Main(string[] args) {
var sw = System.Diagnostics.Stopwatch.StartNew();
var res = gp(15485864); sw.Stop();
double gpt = sw.Elapsed.TotalMilliseconds, tt;
var s = new string[19]; int si = 0;
s[si++] = String.Format("primes gen time: {0} ms", gpt); sw.Restart();
s[si++] = " Nth Primorial";
double y = 0; int x = 1, i = 0, lmt = 10;
s[si++] = String.Format("{0,7} {1}", 0, x);
while (true) {
if (i < 9) s[si++] = String.Format("{0,7} {1}", i + 1, x *= res[i]);
if (i == 8) s[si++] = " Nth Digits Time";
y += Math.Log10(res[i]);
if (++i == lmt) {
s[si++] = String.Format("{0,7} {1,-7} {2,7} ms", lmt, 1 + (int)y,
sw.Elapsed.TotalMilliseconds);
if ((lmt *= 10) > (int)1e6) break; } }
sw.Stop();
Console.WriteLine("{0}\n Tabulation: {1} ms", string.Join("\n", s),
tt = sw.Elapsed.TotalMilliseconds);
Console.Write(" Total:{0} ms", gpt + tt); } }

View file

@ -0,0 +1,75 @@
#include <inttypes.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <gmp.h>
/* Eratosthenes bit-sieve */
int es_check(uint32_t *sieve, uint64_t n)
{
if ((n != 2 && !(n & 1)) || (n < 2))
return 0;
else
return !(sieve[n >> 6] & (1 << (n >> 1 & 31)));
}
uint32_t *es_sieve(const uint64_t nth, uint64_t *es_size)
{
*es_size = nth * log(nth) + nth * (log(log(nth)) - 0.9385f) + 1;
uint32_t *sieve = calloc((*es_size >> 6) + 1, sizeof(uint32_t));
for (uint64_t i = 3; i < sqrt(*es_size) + 1; i += 2)
if (!(sieve[i >> 6] & (1 << (i >> 1 & 31))))
for (uint64_t j = i * i; j < *es_size; j += (i << 1))
sieve[j >> 6] |= (1 << (j >> 1 & 31));
return sieve;
}
size_t mpz_number_of_digits(const mpz_t op)
{
char *opstr = mpz_get_str(NULL, 10, op);
const size_t oplen = strlen(opstr);
free(opstr);
return oplen;
}
#define PRIMORIAL_LIMIT 1000000
int main(void)
{
/* Construct a sieve of the first 1,000,000 primes */
uint64_t sieve_size;
uint32_t *sieve = es_sieve(PRIMORIAL_LIMIT, &sieve_size);
mpz_t primorial;
mpz_init_set_ui(primorial, 1);
uint64_t prime_count = 0;
int print = 1;
double unused;
for (uint64_t i = 2; i < sieve_size && prime_count <= PRIMORIAL_LIMIT; ++i) {
if (print) {
if (prime_count < 10)
gmp_printf("Primorial(%" PRIu64 ") = %Zd\n", prime_count, primorial);
/* Is the current number a power of 10? */
else if (!modf(log10(prime_count), &unused))
printf("Primorial(%" PRIu64 ") has %zu digits\n", prime_count, mpz_number_of_digits(primorial));
print = 0;
}
if (es_check(sieve, i)) {
mpz_mul_ui(primorial, primorial, i);
prime_count++;
print = 1;
}
}
free(sieve);
mpz_clear(primorial);
return 0;
}

View file

@ -0,0 +1,93 @@
% This program uses the 'bigint' cluster from
% the 'misc.lib' included with PCLU.
isqrt = proc (s: int) returns (int)
x0: int := s/2
if x0=0 then return(s) end
x1: int := (x0 + s/x0)/2
while x1 < x0 do
x0 := x1
x1 := (x0 + s/x0)/2
end
return(x0)
end isqrt
sieve = proc (n: int) returns (array[bool])
prime: array[bool] := array[bool]$fill(0,n+1,true)
prime[0] := false
prime[1] := false
for p: int in int$from_to(2, isqrt(n)) do
if prime[p] then
for c: int in int$from_to_by(p*p,n,p) do
prime[c] := false
end
end
end
return(prime)
end sieve
% Calculate the N'th primorial given a boolean array denoting primes
primorial = proc (n: int, prime: array[bool])
returns (bigint) signals (out_of_primes)
% 0'th primorial = 1
p: bigint := bigint$i2bi(1)
for i: int in array[bool]$indexes(prime) do
if ~prime[i] then continue end
if n=0 then break end
p := p * bigint$i2bi(i)
n := n-1
end
if n>0 then signal out_of_primes end
return(p)
end primorial
% Find the length in digits of a bigint without converting it to a string.
% The naive way takes over an hour to count the digits for p(100000),
% this one ~5 minutes.
n_digits = proc (n: bigint) returns (int)
own zero: bigint := bigint$i2bi(0)
own ten: bigint := bigint$i2bi(10)
digs: int := 1
dstep: int := 1
tenfac: bigint := ten
step: bigint := ten
while n >= tenfac do
digs := digs + dstep
step := step * ten
dstep := dstep + 1
next: bigint := tenfac*step
if n >= next then
tenfac := next
else
step, dstep := ten, 1
tenfac := tenfac*step
end
end
return(digs)
end n_digits
start_up = proc ()
po: stream := stream$primary_output()
% Sieve a million primes
prime: array[bool] := sieve(15485863)
% Show the first 10 primorials
for i: int in int$from_to(0,9) do
stream$puts(po, "primorial(" || int$unparse(i) || ") = ")
stream$putright(po, bigint$unparse(primorial(i, prime)), 15)
stream$putl(po, "")
end
% Show the length of some bigger primorial numbers
for tpow: int in int$from_to(1,5) do
p_ix: int := 10**tpow
stream$puts(po, "length of primorial(")
stream$putright(po, int$unparse(p_ix), 7)
stream$puts(po, ") = ")
stream$putright(po, int$unparse(n_digits(primorial(p_ix, prime))), 7)
stream$putl(po, "")
end
end start_up

View file

@ -0,0 +1,46 @@
(ns example
(:gen-class))
; Generate Prime Numbers (Implementation from RosettaCode--link above)
(defn primes-hashmap
"Infinite sequence of primes using an incremental Sieve or Eratosthenes with a Hashmap"
[]
(letfn [(nxtoddprm [c q bsprms cmpsts]
(if (>= c q) ;; only ever equal
; Update cmpsts with primes up to sqrt c
(let [p2 (* (first bsprms) 2),
nbps (next bsprms),
nbp (first nbps)]
(recur (+ c 2) (* nbp nbp) nbps (assoc cmpsts (+ q p2) p2)))
(if (contains? cmpsts c)
; Not prime
(recur (+ c 2) q bsprms
(let [adv (cmpsts c), ncmps (dissoc cmpsts c)]
(assoc ncmps
(loop [try (+ c adv)] ;; ensure map entry is unique
(if (contains? ncmps try)
(recur (+ try adv))
try))
adv)))
; prime
(cons c (lazy-seq (nxtoddprm (+ c 2) q bsprms cmpsts))))))]
(do (def baseoddprms (cons 3 (lazy-seq (nxtoddprm 5 9 baseoddprms {}))))
(cons 2 (lazy-seq (nxtoddprm 3 9 baseoddprms {}))))))
;; Generate Primorial Numbers
(defn primorial [n]
" Function produces the nth primorial number"
(if (= n 0)
1 ; by definition
(reduce *' (take n (primes-hashmap))))) ; multiply first n primes (retrieving primes from lazy-seq which generates primes as needed)
;; Show Results
(let [start (System/nanoTime)
elapsed-secs (fn [] (/ (- (System/nanoTime) start) 1e9))] ; System start time
(doseq [i (concat (range 10) [1e2 1e3 1e4 1e5 1e6])
:let [p (primorial i)]] ; Generate ith primorial number
(if (< i 10)
(println (format "primorial ( %7d ) = %10d" i (biginteger p))) ; Output for first 10
(println (format "primorial ( %7d ) has %8d digits\tafter %.3f secs" ; Output with time since starting for remainder
(long i) (count (str p)) (elapsed-secs))))))

View file

@ -0,0 +1,52 @@
(ns example
(:gen-class))
(defn primes-hashmap
"Infinite sequence of primes using an incremental Sieve or Eratosthenes with a Hashmap"
[]
(letfn [(nxtoddprm [c q bsprms cmpsts]
(if (>= c q) ;; only ever equal
; Update cmpsts with primes up to sqrt c
(let [p2 (* (first bsprms) 2),
nbps (next bsprms),
nbp (first nbps)]
(recur (+ c 2) (* nbp nbp) nbps (assoc cmpsts (+ q p2) p2)))
(if (contains? cmpsts c)
; Not prime
(recur (+ c 2) q bsprms
(let [adv (cmpsts c), ncmps (dissoc cmpsts c)]
(assoc ncmps
(loop [try (+ c adv)] ;; ensure map entry is unique
(if (contains? ncmps try)
(recur (+ try adv))
try))
adv)))
; prime
(cons c (lazy-seq (nxtoddprm (+ c 2) q bsprms cmpsts))))))]
(do (def baseoddprms (cons 3 (lazy-seq (nxtoddprm 5 9 baseoddprms {}))))
(cons 2 (lazy-seq (nxtoddprm 3 9 baseoddprms {}))))))
;; Number of workers (threads) based upon number of available processors
(def workers
(+ 2 (.. Runtime getRuntime availableProcessors)))
;; Generate of primorial numbers (using multiple processors)
(defn primorial [n]
(if (= n 0)
1
;(reduce mul+ (pmap #(reduce *' %) (partition-all (max workers (long (/ n workers))) (take n (primes-hashmap)))))));(*' allows for big integer arithmetic as needed)
(->> ; Threads (i.e. pipes) sequence of expressions
(take n (primes-hashmap) ) ; generate primes
(partition-all (max workers (long (/ n workers)))) ; partition primes amongst workers
(pmap #(reduce *' %)) ; Multiply primes in each worker in parallel
(reduce *')))) ; multiply results of all workers together
;; Generate and Time Output
(let [start (System/nanoTime)
elapsed-secs (fn [] (/ (- (System/nanoTime) start) 1e9))] ; System start time
(doseq [i (concat (range 10) [1e2 1e3 1e4 1e5 1e6])
:let [p (primorial i)]] ; Generate ith primorial number
(if (< i 10)
(println (format "primorial ( %7d ) = %10d" i (biginteger p))) ; Output for first 10
(println (format "primorial ( %7d ) has %8d digits\tafter %.3f secs" ; Output with time since starting for remainder
(long i) (count (str p)) (elapsed-secs))))))

View file

@ -0,0 +1,14 @@
(defun primorial-number-length (n w)
(values (primorial-number n) (primorial-length w)))
(defun primorial-number (n)
(loop for a below n collect (primorial a)))
(defun primorial-length (w)
(loop for a in w collect (length (write-to-string (primorial a)))))
(defun primorial (n &optional (m 1) (k -1) (z 1) &aux (f (primep m)))
(if (= k n) z (primorial n (1+ m) (+ k (if f 1 0)) (if f (* m z) z))))
(defun primep (n)
(loop for a from 2 to (isqrt n) never (zerop (mod n a))))

View file

@ -0,0 +1,57 @@
import std.stdio;
import std.format;
import std.bigint;
import std.math;
import std.algorithm;
int sieveLimit = 1300_000;
bool[] notPrime;
void main()
{
// initialize
sieve(sieveLimit);
// output 1
foreach (i; 0..10)
writefln("primorial(%d): %d", i, primorial(i));
// output 2
foreach (i; 1..6)
writefln("primorial(10^%d) has length %d", i, count(format("%d", primorial(pow(10, i)))));
}
BigInt primorial(int n)
{
if (n == 0) return BigInt(1);
BigInt result = BigInt(1);
for (int i = 0; i < sieveLimit && n > 0; i++)
{
if (notPrime[i]) continue;
result *= BigInt(i);
n--;
}
return result;
}
void sieve(int limit)
{
notPrime = new bool[limit];
notPrime[0] = notPrime[1] = true;
auto max = sqrt(cast (float) limit);
for (int n = 2; n <= max; n++)
{
if (!notPrime[n])
{
for (int k = n * n; k < limit; k += n)
{
notPrime[k] = true;
}
}
}
}

View file

@ -0,0 +1,13 @@
defmodule SieveofEratosthenes do
def init(lim) do
find_primes(2,lim,(2..lim))
end
def find_primes(count,lim,nums) when (count * count) > lim do
nums
end
def find_primes(count,lim,nums) when (count * count) <= lim do
find_primes(count+1,lim,Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)))
end
end

View file

@ -0,0 +1,35 @@
defmodule Primorial do
def first(n,primes) do
s = 0..9 |> Stream.map(fn n -> Enum.at(primes,n) end)
(0..n-1)
|> Enum.map(fn a -> s
|> Enum.take(a)
|> Enum.reduce(1, fn b,c -> b*c end)
|> format(a) end)
end
def numbers(lims,primes) do
numbers(lims,primes,[])
end
def numbers([],_primes,vals) do
vals
|> Enum.reverse
|> Enum.map(fn {m,n} -> str_fr(n,m) end)
end
def numbers([lim|lims],primes,vals) do
numbers(lims,primes,[{lim,number_length(primes,lim)}] ++ vals)
end
defp number_length(primes,n) do
primes
|> Enum.take(n)
|> Enum.reduce(fn a,b -> a * b end)
|> Integer.to_string
|> String.length
end
defp format(pri,i), do: IO.puts("Primorial #{i}: #{pri}")
defp str_fr(pri,i), do: IO.puts("Primorial #{i} has length: #{pri}")
end

View file

@ -0,0 +1,2 @@
Primorial.first(10,SieveofEratosthenes.init(50))
Primorial.numbers([10,100,1_000,10_000,100_000],SieveofEratosthenes.init(1_300_000))

View file

@ -0,0 +1,3 @@
// Primorial Numbers. Nigel Galloway: August 3rd., 2021
primes32()|>Seq.scan((*)) 1|>Seq.take 10|>Seq.iter(printf "%d "); printfn "\n"
[10;100;1000;10000;100000]|>List.iter(fun n->printfn "%d" ((int)(System.Numerics.BigInteger.Log10 (Seq.item n (primesI()|>Seq.scan((*)) 1I)))+1))

View file

@ -0,0 +1,24 @@
USING: formatting kernel literals math math.functions
math.primes sequences ;
IN: rosetta-code.primorial-numbers
CONSTANT: primes $[ 1,000,000 nprimes ]
: digit-count ( n -- count ) log10 floor >integer 1 + ;
: primorial ( n -- m ) primes swap head product ;
: .primorial ( n -- ) dup primorial "Primorial(%d) = %d\n"
printf ;
: .digit-count ( n -- ) dup primorial digit-count
"Primorial(%d) has %d digits\n" printf ;
: part1 ( -- ) 10 iota [ .primorial ] each ;
: part2 ( -- ) { 10 100 1000 10000 100000 1000000 }
[ .digit-count ] each ;
: main ( -- ) part1 part2 ;
MAIN: main

View file

@ -0,0 +1,2 @@
B.DIGIT(I) = MOD(D,BIGBASE)
C = D/BIGBASE

View file

@ -0,0 +1,4 @@
INTEGER*4 D !A 32-bit product.
INTEGER*2 II(2),C,R !Some 16-bit variables.
EQUIVALENCE (D,II) !Align.
EQUIVALENCE (II(1),C),(II(2),R) !Carry in the high order half of D, Result in the low.

View file

@ -0,0 +1,194 @@
MODULE BIGNUMBERS !Limited services: decimal integers, no negative numbers.
INTEGER BIGORDER !A limit attempt at generality.
PARAMETER (BIGORDER = 2) !This is the order of the base of the big number arithmetic.
INTEGER BIGBASE,BIGLIMIT !Sized thusly.
PARAMETER (BIGBASE = 10**BIGORDER, BIGLIMIT = 8888888/BIGORDER) !Enough?
TYPE BIGNUM !So, a big number is simple.
INTEGER LAST !This many digits (of size BIGBASE) are in use.
INTEGER DIGIT(BIGLIMIT) !The digits, in ascending power order.
END TYPE BIGNUM !So much for that.
CONTAINS !Now for some assistants.
SUBROUTINE BIGMULT(B,N) !B:=B*N; Multiply by an integer possibly bigger than the base.
TYPE(BIGNUM) B !The worker.
INTEGER N !A computer number, not a multi-digit number.
INTEGER D !Must be able to hold (BIGBASE - 1)*N + C
INTEGER C !The carry to the next digit.
INTEGER I !A stepper.
C = 0 !No previous digit to carry from.
DO I = 1,B.LAST !Step through the digits, upwards powers.
D = B.DIGIT(I) !Grab a digit.
D = D*N + C !Apply the multiply.
B.DIGIT(I) = MOD(D,BIGBASE) !Place the resulting digit.
C = D/BIGBASE !Agony! TWO divisions per step!!
END DO !On to the next digit up.
DO WHILE(C .GT. 0) !Now spread the last carry to further digits.
B.LAST = B.LAST + 1 !Up one more.
IF (B.LAST .GT. BIGLIMIT) STOP "Overflow by multiply!" !Perhaps not.
B.DIGIT(B.LAST) = MOD(C,BIGBASE) !The digit.
C = C/BIGBASE !The carry may be large, if N is large.
END DO !So slog on until it is gone.
END SUBROUTINE BIGMULT !Primary school stuff.
END MODULE BIGNUMBERS !No fancy tricks.
MODULE ERATOSTHENES !Prepare an array of prime numbers.
Considers odd numbers only as the pattern is very simple. Some trickery as a consequence.
INTEGER NP,LASTP !Counters.
PARAMETER (LASTP = 1000000) !The specified need.
INTEGER PRIME(0:LASTP),PREZAP !Initialisation is rather messy.
PARAMETER (PREZAP = 6) !Up to PRIME(6) = 13.
DATA NP/PREZAP/, PRIME(0:PREZAP)/1,2,3,5,7,11,13/ !Not counting the "zeroth" prime, 1.
CONTAINS !Some tricky stuff/
SUBROUTINE PREPARE PRIMES !Fetch a limited copy of the Platonic ideal.
INTEGER SURGE,LB !A sieve has a certain rather special size.
PARAMETER (SURGE = 30030, LB = SURGE/2 - 1) != 2*3*5*7*11*13.
LOGICAL*1 BIT(0:LB),START(0:LB)!Two such arrays, thanks.
INTEGER N0,NN !Bounds for the current sieve span.
INTEGER I,P,IP !Assistants.
C The scheme for a cycle of 2*3*5 = 30, remembering that even numbers are not involved so BIT(0:14).
C | surge 1 | surge 2 | surge 3 |
C N = | 1 1 1 1 1 2 2 2 2 2|3 3 3 3 3 4 4 4 4 4 5 5 5 5 5|6 6 6 6 6 7 7 7 7 7 8 8 8 8 8|9 9 9 9 9...
C |1 3 5 7 9 1 3 5 7 9 1 3 5 7 9|1 3 5 7 9 1 3 5 7 9 1 3 5 7 9|1 3 5 7 9 1 3 5 7 9 1 3 5 7 9|1 3 5 7 9...
C BIT(index) | 1 1 1 1 1| 1 1 1 1 1| 1 1 1 1 1|
C |0 1 2 3 4 5 6 7 8 9 0 1 2 3 4|0 1 2 3 4 5 6 7 8 9 0 1 2 3 4|0 1 2 3 4 5 6 7 8 9 0 1 2 3 4|0 1 2 3 4...
c 3 step | * * * * * | * * * * * | * * * * * | * *
c 5 step | * * * | * * * | * * * | *
c 7 step | x x | x * | * * |*
Concoct the initial state, once only, that repeats every SURGE.
START = .TRUE. !Prepare the field.
DO I = 2,PREZAP !Only odd numbers are represented, so no PRIME(1) = 2..
P = PRIME(I) !Select a step.
START(P/2:LB:P) = .FALSE. !Knock out multiples of P.
END DO !This pattern is palindromic.
NN = 0 !Syncopation. Where the previous surge ended.
Commence a pass through the BIT sieve.
10 N0 = NN !BIT(0) corresponds to N0 + 1, BIT(i) to N0 + 1 + 2i.
NN = NN + SURGE !BIT(LB) to NN - 1.
BIT = START !Pre-zapped for lesser primes.
IP = PREZAP !Syncopation. The last pre-zapped prime.
11 IP = IP + 1 !The next prime to sieve with.
IF (IP.GT.NP) CALL SCANFOR(.TRUE.) !Whoops, not yet to hand!
P = PRIME(IP) !Now grab it.
IF (P*P.GE.NN) GO TO 12 !If P*P exceeds the end, so will larger P.
I = N0/P + 1 !First multiple of P past N0.
IF (I.LT.P) I = P !Less than P is superfluous: the position was zapped by earlier action.
IF (MOD(I,2).EQ.0) I = I + 1 !If even, advance to the next odd multiple. Such as P.
I = I*P !The first number to zap. It will always be odd.
IF (I.LT.NN) THEN !Within the span?
I = (I - N0 - 1)/2 !Yes. Its offset into the current span.
BIT(I:LB:P) = .FALSE. !Zap every P'th position.
END IF !So much for that P.
GO TO 11 !On to the next.
Completed the passes. Scan for survivors.
12 CALL SCANFOR(.FALSE.) !All, not just the first new prime.
IF (NP.LT.LASTP) GO TO 10 !Another batch?
RETURN !Done.
CONTAINS !Fold two usages into one routine.
SUBROUTINE SCANFOR(ONE) !Finds survivors.
LOGICAL ONE !Perhaps only the first is desired.
INTEGER I,P !Assistants.
DO I = 0,LB !Scan the current state.
IF (BIT(I)) THEN !Is this one unsullied?
P = N0 + 1 + 2*I !Yes! This is its value.
IF (P.LE.PRIME(NP)) CYCLE !But we may have it already.
IF (NP.GE.LASTP) RETURN !Whoops, perhaps too many!
NP = NP + 1 !But if not, another new prime!
PRIME(NP) = P !So, stash it. Extract now just this one.
IF (ONE) RETURN !Later candidates may yet be unzapped.
END IF !So much for that value.
END DO !On to the next.
END SUBROUTINE SCANFOR !An odd IF allows for two usages in one routine.
END SUBROUTINE PREPARE PRIMES !Faster than reading from a disc file?
END MODULE ERATOSTHENES !Certainly, less storage is required this way.
PROGRAM PRIMORIAL !Simple enough, with some assistants.
USE ERATOSTHENES !Though probably not as he expected.
USE BIGNUMBERS !Just so.
TYPE(BIGNUM) B !I'll have one.
INTEGER P,MARK !Step stuff.
INTEGER E,D !Assistants for the floating-point analogue...
INTEGER TASTE,IT !Additional stuff for its rounding.
PARAMETER (TASTE = 8/BIGORDER) !Sufficient digits to show.
INTEGER LEAD(TASTE) !With a struggle.
REAL T0,T1 !Some CPU time attempts.
REAL*4 F4 !I'll also have a go via logs.
REAL*8 F8 !In two precisions.
INTEGER I4,I8 !Not much hope for single precision, though.
WRITE (6,1) LASTP,BIGBASE !Announce.
1 FORMAT ("Calculates primorial numbers up to prime ",I0,
1 ", working in base ",I0)
CALL PREPARE PRIMES !First, catch your rabbit.
Commence prime mashing.
100 B.LAST = 1 !Begin at the beginning.
B.DIGIT(1) = 1 !With one.
DO P = 0,9 !Step up to the ninth prime, thus the first ten values as specified.
CALL BIGMULT(B,PRIME(P)) !Multiply by a possibly large integer.
WRITE (6,101) P,PRIME(P),P,B.DIGIT(B.LAST:1:-1) !Digits in Arabic/Hindu order.
101 FORMAT ("Prime(",I0,") = ",I0,", Primorial(",I0,") = ",
1 I0,9I<BIGORDER>.<BIGORDER>,/,(10I<BIGORDER>.<BIGORDER>))
END DO !On to the next prime.
Convert to logarithmic striders.
CALL CPU_TIME(T0) !Start the clock.
MARK = 10 !To be remarked upon in passing.
DO P = 10,LASTP !Step through additional primes.
CALL BIGMULT(B,PRIME(P)) !Bigger, ever bigger the big number grows.
IF (P.EQ.MARK) THEN !A report point?
MARK = MARK*10 !Yes. Prepare to note the next.
CALL CPU_TIME(T1) !Where are we at?
E = (B.LAST - 1)*BIGORDER !Convert from 10**BIGORDER to base 10.
D = B.DIGIT(B.LAST) !Grab the high-order digit.
DO WHILE(D.GT.0) !It is not zero..
E = E + 1 !So it is at least one base ten digit.
D = D/10 !Snip.
END DO !And perhaps there will be more.
Contemplate the rounding of the floating-point analogue.
I4 = MIN(TASTE,B.LAST) !I'm looking to taste the top digits.
LEAD(1:I4) = B.DIGIT(B.LAST:B.LAST - I4 + 1:-1) !Reverse, to have normal order.
IF (B.LAST.GT.TASTE) THEN !Are there even more digits?
IT = I4 !Yes. This is now the low-order digit tasted.
D = 0 !We should consider rounding up.
IF (B.DIGIT(B.LAST - I4).GE.BIGBASE/2) D = 1 !If the next digit is big enough.
DO WHILE (D.GT.0) !Spread the carry.
D = 0 !This one is used up.
LEAD(IT) = LEAD(IT) + 1 !Thusly.
IF (LEAD(IT).GT.BIGBASE) THEN !But, maybe, overflow!
IF (IT.GT.1) THEN !Is there a higher-order to carry to?
LEAD(IT) = LEAD(IT) - BIGBASE !Yes!
IT = IT - 1 !Step back to it,
D = 1 !Reassert a carry.
END IF !But only if there was a recipient available.
END IF !If not, the carry will still be zero.
END DO !And the loop won't continue.
END IF !So, no test for IT > 0 in a compound "while".
Cast forth the results.
WRITE (6,102) P,PRIME(P), !Name the step and its prime.
1 P,LEAD(1:I4),E, !The step and the leading few DIGIT of its primorial.
2 T1 - T0 !CPU advance.
102 FORMAT ("Prime(",I0,") = ",I0,", Primorial(",I0,") ~ 0." !Approximately.
1 I0,<I4 - 1>I<BIGORDER>.<BIGORDER>,"E+",I0, !No lead zero digits, then with lead zero digits.
2 T80,F12.3," seconds.") !Append some CPU time information.
T0 = T1 !Ready for the next popup.
END IF !So much for a report.
END DO !On to the next prime.
Chew some logarithms.
110 WRITE (6,111) !Some explanation.
111 FORMAT (/,"Via summing logarithms: Single Double") !Ah, layout.
MARK = 10 !Start somewhere interesting.
112 F4 = SUM(LOG10( FLOAT(PRIME(1:MARK)))) !Whee!
F8 = SUM(LOG10(DFLOAT(PRIME(1:MARK)))) !Generic function names too.
I4 = F4 !Grab the integer part.
I8 = F8 !The idea being to isolate the fractional part.
WRITE (6,113) MARK,"10",10**(F4 - I4),I4 + 1,10**(F8 - I8),I8 + 1 !Reconstitute the number in extended E-format.
113 FORMAT (I8,"#...in base ",A2,-1PF9.5,"E+",I0,T40,-1PF13.7,"E+",I0) !As if via E-format.
F4 = SUM(LOG( FLOAT(PRIME(1:MARK))))/LOG(10.0) !Do it again in Naperian logs.
F8 = SUM(LOG(DFLOAT(PRIME(1:MARK))))/LOG(10D0) !Perhaps more accurately?
I4 = F4
I8 = F8
WRITE (6,113) MARK,"e ",10**(F4 - I4),I4 + 1,10**(F8 - I8),I8 + 1 !We'll see.
MARK = MARK*10 !The next reporting point.
IF (MARK.LE.LASTP) GO TO 112 !Are we there yet?
END !So much for that.

View file

@ -0,0 +1,97 @@
' version 22-09-2015
' compile with: fbc -s console
Const As UInteger Base_ = 1000000000
ReDim Shared As UInteger primes()
Sub sieve(need As UInteger)
' estimate is to high, but ensures that we have enough primes
Dim As UInteger max = need * (Log(need) + Log(Log(need)))
Dim As UInteger t = 1 ,x , x2
Dim As Byte p(max)
ReDim primes (need + need \ 3) ' we trim the array later
primes(0) = 1 ' by definition
primes(1) = 2 ' first prime, the only even prime
' only consider the odd number
For x = 3 To Sqr(max) Step 2
If p(x) = 0 Then
For x2 = x * x To max Step x * 2
p(x2) = 1
Next
End If
Next
' move found primes to array
For x = 3 To max Step 2
If p(x) = 0 Then
t += 1
primes(t) = x
EndIf
Next
'ReDim Preserve primes(t)
ReDim Preserve primes(need)
End Sub
' ------=< MAIN >=------
Dim As UInteger n, i, pow, primorial
Dim As String str_out, buffer = Space(10)
Dim As UInteger max = 100000 ' maximum number of primes we need
sieve(max)
primorial = 1
Print
For n = 0 To 9
primorial = primorial * primes(n)
Print Using " primorial(#) ="; n;
RSet buffer, Str(primorial)
str_out = buffer
Print str_out
Next
' could use GMP, but why not make are own big integer routine
Dim As UInteger bigint(max), first = max, last = max
Dim As UInteger l, p, carry, low = 9, high = 10
Dim As ULongInt result
Dim As UInteger Ptr big_i
' start at the back, number grows to the left like normal number
bigint(last) = primorial
Print
For pow = 0 To Len(Str(max)) -2
If pow > 0 Then
low = high
high = high * 10
End If
For n = low + 1 To high
carry = 0
big_i = @bigint(last)
For i = last To first Step -1
result = CULngInt(primes(n)) * *big_i + carry
carry = result \ Base_
*big_i = result - carry * Base_
big_i = big_i -1
Next i
If carry <> 0 Then
first = first -1
*big_i = carry
End If
Next n
l = Len(Str(bigint(first))) + (last - first) * 9
Print " primorial("; high; ") has "; l ;" digits"
Next pow
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,7 @@
primorial[n] := product[first[primes[], n]]
for n = 0 to 9
println["primorial[$n] = " + primorial[n]]
for n = [10, 100, 1000, 10000, 100000, million]
println["Length of primorial $n is " + length[toString[primorial[n]]] + " decimal digits."]

View file

@ -0,0 +1,31 @@
/** Calculate the primes and set up for the recursive call. */
primorialSplitting[n] :=
{
if n == 0
return 1
primes = array[first[primes[], n]]
return primorialSplitting[n, 0, n-1, primes]
}
/** The actual recursive algorithm. */
primorialSplitting[n, begin, end, primes] :=
{
range = (end-begin)
if range >= 2
{
middle = (begin + end) div 2
return primorialSplitting[n, begin, middle, primes] * primorialSplitting[n, middle+1, end, primes]
}
if range == 1
return primes@begin * primes@end
if range == 0
return primes@begin
}
for n = 0 to 9
println["primorial[$n] = " + primorialSplitting[n]]
for n = [10, 100, 1000, 10000, 100000, million]
println["Length of primorial $n is " + length[toString[primorialSplitting[n]]] + " decimal digits."]

View file

@ -0,0 +1,30 @@
package main
import (
"fmt"
"math/big"
"time"
"github.com/jbarham/primegen.go"
)
func main() {
start := time.Now()
pg := primegen.New()
var i uint64
p := big.NewInt(1)
tmp := new(big.Int)
for i <= 9 {
fmt.Printf("primorial(%v) = %v\n", i, p)
i++
p = p.Mul(p, tmp.SetUint64(pg.Next()))
}
for _, j := range []uint64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
for i < j {
i++
p = p.Mul(p, tmp.SetUint64(pg.Next()))
}
fmt.Printf("primorial(%v) has %v digits", i, len(p.String()))
fmt.Printf("\t(after %v)\n", time.Since(start))
}
}

View file

@ -0,0 +1,48 @@
package main
import (
"fmt"
"github.com/jbarham/primegen"
big "github.com/ncw/gmp"
"time"
)
func vecprod(primes []uint64) *big.Int {
if len(primes) == 0 {
return big.NewInt(1)
}
s := make([]*big.Int, len(primes))
le := len(s)
for i := 0; i < le; i++ {
s[i] = new(big.Int).SetUint64(primes[i])
}
for le > 1 {
for i := 0; i < le/2; i++ {
s[i].Mul(s[i], s[le-i-1])
}
c := le / 2
if le&1 == 1 {
c++
}
s = s[0:c]
le = c
}
return s[0]
}
func main() {
start := time.Now()
pg := primegen.New()
var primes []uint64
for i := uint64(0); i < 1e6; i++ {
primes = append(primes, pg.Next())
}
for i := 0; i < 10; i++ {
fmt.Printf("primorial(%d) = %d\n", i, vecprod(primes[0:i]))
}
fmt.Println()
for _, i := range []uint64{1e1, 1e2, 1e3, 1e4, 1e5, 1e6} {
fmt.Printf("primorial(%d) has length %d\n", i, len(vecprod(primes[0:i]).String()))
}
fmt.Printf("\nTook %s\n", time.Since(start))
}

View file

@ -0,0 +1,31 @@
import Control.Arrow ((&&&))
import Data.List (scanl1, foldl1')
getNthPrimorial :: Int -> Integer
getNthPrimorial n = foldl1' (*) (take n primes)
primes :: [Integer]
primes = 2 : filter isPrime [3,5..]
isPrime :: Integer -> Bool
isPrime = isPrime_ primes
where isPrime_ :: [Integer] -> Integer -> Bool
isPrime_ (p:ps) n
| p * p > n = True
| n `mod` p == 0 = False
| otherwise = isPrime_ ps n
primorials :: [Integer]
primorials = 1 : scanl1 (*) primes
main :: IO ()
main = do
-- Print the first 10 primorial numbers
let firstTen = take 10 primorials
putStrLn $ "The first 10 primorial numbers are: " ++ show firstTen
-- Show the length of the primorials with index 10^[1..6]
let powersOfTen = [1..6]
primorialTens = map (id &&& (length . show . getNthPrimorial . (10^))) powersOfTen
calculate = mapM_ (\(a,b) -> putStrLn $ "Primorial(10^"++show a++") has "++show b++" digits")
calculate primorialTens

View file

@ -0,0 +1 @@
primorial=:*/@:p:@i."0

View file

@ -0,0 +1,14 @@
primorial i. 10 NB. first 10 primorial numbers
1 2 6 30 210 2310 30030 510510 9699690 223092870
#":primorial 10x NB. lengths (of decimal representations)...
10
#":primorial 100x
220
#":primorial 1000x
3393
#":primorial 10000x
45337
#":primorial 100000x
563921
#":primorial 1000000x
6722809

View file

@ -0,0 +1,45 @@
import java.math.BigInteger;
public class PrimorialNumbers {
final static int sieveLimit = 1300_000;
static boolean[] notPrime = sieve(sieveLimit);
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.printf("primorial(%d): %d%n", i, primorial(i));
for (int i = 1; i < 6; i++) {
int len = primorial((int) Math.pow(10, i)).toString().length();
System.out.printf("primorial(10^%d) has length %d%n", i, len);
}
}
static BigInteger primorial(int n) {
if (n == 0)
return BigInteger.ONE;
BigInteger result = BigInteger.ONE;
for (int i = 0; i < sieveLimit && n > 0; i++) {
if (notPrime[i])
continue;
result = result.multiply(BigInteger.valueOf(i));
n--;
}
return result;
}
public static boolean[] sieve(int limit) {
boolean[] composite = new boolean[limit];
composite[0] = composite[1] = true;
int max = (int) Math.sqrt(limit);
for (int n = 2; n <= max; n++) {
if (!composite[n]) {
for (int k = n * n; k < limit; k += n) {
composite[k] = true;
}
}
}
return composite;
}
}

View file

@ -0,0 +1,16 @@
def primes:
2, range(3; infinite; 2) | select(is_prime);
# generate an infinite stream of primorials beginning with primorial(0)
def primorials:
0, foreach primes as $p (1; .*$p; .);
"The first ten primorial numbers are:",
limit(10; primorials),
"\nThe primorials with the given index have the lengths shown:",
([10, 100, 1000, 10000, 100000] as $sample
| limit($sample|length;
foreach primes as $p ([0,1]; # [index, primorial]
.[0]+=1 | .[1] *= $p;
select(.[0]|IN($sample[])) | [.[0], (.[1]|tostring|length)] ) ))

View file

@ -0,0 +1,14 @@
using Primes
primelist = primes(300000001) # primes to 30 million
primorial(n) = foldr(*, primelist[1:n], init=BigInt(1))
println("The first ten primorials are: $([primorial(n) for n in 1:10])")
for i in 1:6
n = 10^i
p = primorial(n)
plen = Int(floor(log10(p))) + 1
println("primorial($n) has length $plen digits in base 10.")
end

View file

@ -0,0 +1,46 @@
// version 1.0.6
import java.math.BigInteger
const val LIMIT = 1000000 // expect a run time of about 20 minutes on a typical laptop
fun isPrime(n: Int): Boolean {
if (n < 2) return false
if (n % 2 == 0) return n == 2
if (n % 3 == 0) return n == 3
var d : Int = 5
while (d * d <= n) {
if (n % d == 0) return false
d += 2
if (n % d == 0) return false
d += 4
}
return true
}
fun countDigits(bi: BigInteger): Int = bi.toString().length
fun main(args: Array<String>) {
println("Primorial(0) = 1")
println("Primorial(1) = 2")
var count = 1
var p = 3
var prod = BigInteger.valueOf(2)
var target = 10
while(true) {
if (isPrime(p)) {
count++
prod *= BigInteger.valueOf(p.toLong())
if (count < 10) {
println("Primorial($count) = $prod")
if (count == 9) println()
}
else if (count == target) {
println("Primorial($target) has ${countDigits(prod)} digits")
if (count == LIMIT) break
target *= 10
}
}
p += 2
}
}

View file

@ -0,0 +1,22 @@
-- libs
sieve = script("math.primes").new()
bigint = script("bigint").new()
cnt = 1000 * 100
primes = sieve.getNPrimes(cnt)
pr = 1
put "Primorial 0: " & pr
repeat with i = 1 to 9
pr = pr*primes[i]
put "Primorial " & i & ": " & pr
end repeat
pow10 = 10
repeat with i = 10 to cnt
pr = bigint.mul(pr, primes[i])
if i mod pow10=0 then
put "Primorial " & i & " has length: " & pr.length
pow10 = pow10 * 10
end if
end repeat

View file

@ -0,0 +1,29 @@
with(NumberTheory):
primorial := proc(n::integer)
local total := 1:
local count:
for count from 1 to n do
total *= ithprime(count):
end:
return total;
end proc:
primorialDigits := proc(n::integer)
local logSum := 0:
local count:
for count from 1 to n do
logSum += log10(ithprime(count)):
end:
return ceil(logSum);
end proc:
print("The first 10 primorial numbers");
for count from 0 to 9 do
cat("primorial(", count, ") = ", primorial(count))
end;
for expon from 1 to 5 do
cat("primorial(", 10^expon, ") has ", primorialDigits(10^expon), " digits");
end;

View file

@ -0,0 +1 @@
FoldList[Times, 1, Prime @ Range @ 9]

View file

@ -0,0 +1 @@
primes = Prime @ Range[10^6];

View file

@ -0,0 +1 @@
primorial[n_]:= Times @@ primes[[;;n]]

View file

@ -0,0 +1,3 @@
Grid@Table[{"primorial(10^" <> ToString[n] <> ") has ",
{timing,answer}=AbsoluteTiming[IntegerLength@primorial[10^n]];answer,
" digits in "<>ToString@timing<>" seconds"}, {n,6}]

View file

@ -0,0 +1,32 @@
library "prime_sieve.5c"
# For 1 million primes
# int val = 15485867;
int val = 1299743;
int start = millis();
int [*] primes = PrimeSieve::primes(val);
printf("%d primes (%d) in %dms\n", dim(primes), primes[dim(primes)-1], millis() - start);
int primorial(int n) {
if (n == 0) return 1;
if (n == 1) return 2;
int v = 2;
for (int i = 2; i <= n; i++) {
v *= primes[i-2];
}
return v;
}
for (int i = 0; i < 10; i++) {
printf("primorial(%d) = %d\n", i, primorial(i));
}
for (int i = 1; i < 6; i++) {
start = millis();
int p = 10**i;
int pn = primorial(p);
int digits = floor(Math::log10(pn)) + 1;
printf("primorial(%d) has %d digits, in %dms\n", p, digits, millis() - start);
}

View file

@ -0,0 +1,61 @@
import times
let t0 = cpuTime()
####################################################################################################
# Build list of primes.
const
NPrimes = 1_000_000
N = 16 * NPrimes
var sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.
for i, composite in sieve:
if not composite:
let n = 2 * i + 3
for k in countup(n * n, N, 2 * n):
sieve[(k - 3) div 2] = true
var primes = @[2]
for i, composite in sieve:
if not composite:
primes.add 2 * i + 3
if primes.len < NPrimes:
quit "Not enough primes. Please, increase value of N."
####################################################################################################
# Compute primorial.
import strformat
import bignum
const LastToPrint = NPrimes
iterator primorials(): Int =
## Yield successive primorial numbers.
var prim = newInt(1)
yield prim
for p in primes:
prim *= p
yield prim
var n = 0
for prim in primorials():
echo &"primorial({n}) = {prim}"
inc n
if n == 10: break
n = 0
var nextToPrint = 10
for prim in primorials():
if n == nextToPrint:
echo &"primorial({n}) has {($prim).len} digits"
if nextToPrint == LastToPrint: break
nextToPrint *= 10
inc n
echo ""
echo &"Total time: {cpuTime() - t0:.2f} s"

View file

@ -0,0 +1,69 @@
import std/monotimes
let t0 = getMonoTime()
####################################################################################################
# Build list of primes.
const
NPrimes = 1_000_000
N = 16 * NPrimes
var sieve: array[(N - 1) div 2 + 1, bool] # False (default) means prime.
for i, composite in sieve:
if not composite:
let n = 2 * i + 3
for k in countup(n * n, N, 2 * n):
sieve[(k - 3) div 2] = true
var primes = @[2]
for i, composite in sieve:
if not composite:
primes.add 2 * i + 3
if primes.len < NPrimes:
quit "Not enough primes. Please, increase value of N."
####################################################################################################
# Compute primorial.
import strformat, threadpool
import bignum
const NWorkers = 8
proc computeProduct(a: openArray[int]): Int =
result = newInt(1)
for n in a: result *= n
proc primorial(n: int): Int =
if n == 0: return newInt(1)
# Prepare sublists.
var input: array[NWorkers, seq[int]]
for i in 0..<n:
input[i mod NWorkers].add primes[i]
# Spawn workers and get partial products.
var responses: array[NWorkers, FlowVar[Int]]
for i in 0..<NWorkers:
responses[i] = spawn computeProduct(input[i])
# Compute final product.
result = ^responses[0]
for i in 1..<NWorkers:
result *= ^responses[i]
for n in 0..9:
echo &"primorial({n}) = {primorial(n)}"
for n in [10, 100, 1_000, 10_000, 1_000_000]:
echo &"primorial({n}) has {len($primorial(n))} digits"
echo ""
echo &"Total time: {(getMonoTime() - t0)}"

View file

@ -0,0 +1,4 @@
nthprimorial(n)=prod(i=1,n,prime(i));
vector(10,i,nthprimorial(i-1))
vector(5,n,#Str(nthprimorial(10^n)))
#Str(nthprimorial(10^6))

View file

@ -0,0 +1,2 @@
nthprimorial(n)=vecprod(primes(n));
vector(6,n,#Str(nthprimorial(10^n)))

View file

@ -0,0 +1,31 @@
{$H+}
uses
sysutils,mp_types,mp_base,mp_prime,mp_numth;
var
x: mp_int;
t0,t1: TDateTime;
s: AnsiString;
var
i,cnt : NativeInt;
ctx :TPrimeContext;
begin
mp_init(x);
cnt := 1;
i := 2;
FindFirstPrime32(i,ctx);
i := 10;
t0 := time;
repeat
repeat
FindNextPrime32(ctx);
inc(cnt);
until cnt = i;
mp_primorial(ctx.prime,x);
s:= mp_adecimal(x);
writeln('MaxPrime ',ctx.prime:10,length(s):8,' digits');
i := 10*i;
until i > 1000*1000;
t1 := time;
Writeln((t1-t0)*86400.0:10:3,' s');
end.

View file

@ -0,0 +1,110 @@
program Primorial;
{$IFDEF FPC} {$MODE DELPHI} {$ENDIF}
uses
sysutils;
var
primes : array[0..1000000] of LongInt;
procedure InitSieve;
const
HiSieve = 15485864;
var
sieve: array of boolean;
i, j: NativeInt;
Begin
setlength(sieve,HiSieve);
fillchar(sieve[0],HiSieve,chr(ord(True)));
For i := 2 to Trunc(sqrt(HiSieve)) do
IF sieve[i] then Begin
j := i*i;repeat sieve[j]:= false;inc(j,i);until j>= HiSieve-1;end;
i:= 2;j:= 1;
repeat
IF sieve[i] then begin primes[j]:= i;inc(j) end;
inc(i);
until i > HiSieve;
primes[0] := 1;setlength(sieve,0);
end;
function getPrimorial(n:NativeInt):Uint64;
Begin
result := ORD(n>=0);
IF (n >= 0) AND (n < 16) then
repeat result := result*primes[n]; dec(n); until n < 1;
end;
function getPrimorialDecDigits(n:NativeInt):NativeInt;
var
res: extended;
Begin
result := -1;
IF (n > 0) AND (n <= 1000*1000) then
Begin
res := 0;
repeat res := res+ln(primes[n]); dec(n); until n < 1;
result := trunc(res/ln(10))+1;
end;
end;
function getPrimorialExact(n:NativeInt):NativeInt;
const
LongWordDec = 1000000000;
var
MulArr : array of LongWord;
pMul : ^LongWord;
Mul1,prod,carry : Uint64;
i,j,ul : NativeInt;
begin
i := getPrimorialDecDigits(n) DIV 9 +10;
Setlength(MulArr,i);
Ul := 0;
MulArr[Ul]:= 1;
i := 1;
repeat
Mul1 := 1;
//Make Mul1 as large as possible
while (i<= n) AND ((LongWordDec DIV MUL1) >= primes[i]) do
Begin Mul1 := Mul1*primes[i]; inc(i); end;
carry := 0;
pMul := @MulArr[0];
For j := 0 to UL do
Begin
prod := Mul1*pMul^+Carry;
Carry := prod Div LongWordDec;
pMul^ := Prod - Carry*LongWordDec;
inc(pMul);
end;
IF Carry <> 0 then Begin inc(Ul);pMul^:= Carry; End;
until i> n;
//count digits
i := Ul*9;
Carry := MulArr[Ul];
repeat
Carry := Carry DIV 10;
inc(i);
until Carry = 0;
result := i;
end;
var
i: NativeInt;
Begin
InitSieve;
write('Primorial (0->9) ');
For i := 0 to 9 do
write(getPrimorial(i),',');
writeln(#8#32#13#10);
i:= 10;
repeat
writeln('Primorial (',i,') = digits ',
getPrimorialDecDigits(i),' digits');
i := i*10;
until i> 1000000;
writeln;
i:= 10;
repeat
writeln('PrimorialExact (',i,') = digits ',
getPrimorialExact(i),' digits');
i := i*10;
until i> 100000;
end.

View file

@ -0,0 +1,5 @@
use ntheory qw(pn_primorial);
say "First ten primorials: ", join ", ", map { pn_primorial($_) } 0..9;
say "primorial(10^$_) has ".(length pn_primorial(10**$_))." digits" for 1..6;

View file

@ -0,0 +1,2 @@
use ntheory ":all";
say length( vecprod( @{primes( nth_prime(10**6) )} ) );

View file

@ -0,0 +1,35 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">vecprod</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">={}</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">else</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">while</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)></span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">mpz_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[-</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #7060A8;">ceil</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">(),</span>
<span style="color: #000000;">max10</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">JS</span><span style="color: #0000FF;">?</span><span style="color: #000000;">4</span><span style="color: #0000FF;">:</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">9</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)&</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">max10</span><span style="color: #0000FF;">)),</span>
<span style="color: #000000;">primes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">get_primes</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ti</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tests</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #004080;">mpz</span> <span style="color: #000000;">primorial</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">vecprod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primes</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">])</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">ps</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ti</span><span style="color: #0000FF;"><</span><span style="color: #000000;">10</span><span style="color: #0000FF;">?</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"= %s"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primorial</span><span style="color: #0000FF;">,</span><span style="color: #000000;">comma_fill</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)})</span>
<span style="color: #0000FF;">:</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"has %,d digits"</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">mpz_sizeinbase</span><span style="color: #0000FF;">(</span><span style="color: #000000;">primorial</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Primorial(%,d) %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">ti</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ps</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">elapsed</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,28 @@
(de prime? (N Lst)
(let S (sqrt N)
(for D Lst
(T (> D S) T)
(T (=0 (% N D)) NIL) ) ) )
(de take (N)
(let I 1
(make
(link 2)
(do (dec N)
(until (prime? (inc 'I 2) (made)))
(link I) ) ) ) )
# This is a simple approach to calculate primorial may not be the fastest one
(de primorial (N)
(apply * (take N)) )
#print 1st 10 primorial numbers
(for M 10 (prinl "primorial: "(primorial M)))
# print the length of primorial numbers.
[prinl (length (primorial (** 10 1)]
[prinl (length (primorial (** 10 2)]
[prinl (length (primorial (** 10 3)]
[prinl (length (primorial (** 10 4)]
#The last one takes a very long time to compute.
[prinl (length (primorial (** 10 5)]

View file

@ -0,0 +1,14 @@
from pyprimes import nprimes
from functools import reduce
primelist = list(nprimes(1000001)) # [2, 3, 5, ...]
def primorial(n):
return reduce(int.__mul__, primelist[:n], 1)
if __name__ == '__main__':
print('First ten primorals:', [primorial(n) for n in range(10)])
for e in range(7):
n = 10**e
print('primorial(%i) has %i digits' % (n, len(str(primorial(n)))))

View file

@ -0,0 +1,23 @@
[ 0 swap
[ dip 1+
10 /
dup 0 = until ]
drop ] is digits ( n --> n )
[ stack ] is primorials ( --> s )
1299710 eratosthenes
' [ 1 ]
1299710 times
[ i^ isprime if
[ i^ over -1 peek * join ] ]
primorials put
primorials share 10 split drop echo
cr
[] 6 times
[ primorials share
10 i^ ** peek
digits join ]
echo

View file

@ -0,0 +1,43 @@
/*REXX program computes some primorial numbers for low numbers, and for various 10^n.*/
parse arg N H . /*get optional arguments: N, L, H */
if N=='' | N==',' then N= 10 /*Not specified? Then use the default.*/
if H=='' | H==',' then H= 100000 /* " " " " " " */
numeric digits 600000 /*be able to handle gihugic numbers. */
w= length( commas( digits() ) ) /*W: width of the largest commatized #*/
@.=.; @.0= 1; @.1= 2; @.2= 3; @.3= 5; @.4= 7; @.5= 11; @.6= 13 /*some low primes.*/
s.1= 4; s.2= 9; s.3= 25; s.4= 49; s.5= 121; s.6= 169 /*squared primes. */
#= 6 /*number of primes*/
do j=0 for N /*calculate the first N primorial #s.*/
say right(j, length(N))th(j) " primorial is: " right(commas(primorial(j) ), N+2)
end /*j*/
say
iw= length( commas(H) ) + 2 /*IW: width of largest commatized index*/
p= 1 /*initialize the first multiplier for P*/
do k=1 for H /*process a large range of numbers. */
p= p * prime(k) /*calculate the next primorial number. */
parse var k L 2 '' -1 R /*get the left and rightmost dec digits*/
if R\==0 then iterate /*if right─most decimal digit\==0, skip*/
if L\==1 then iterate /* " left─most " " \==1, " */
if strip(k, , 0)\==1 then iterate /*Not a power of 10? Then skip this K.*/
say right( commas(k), iw)th(k) ' primorial number length in decimal digits is:' ,
right( commas( length(p) ), w)
end /*k*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg _; do ?=length(_)-3 to 1 by -3; _=insert(',', _, ?); end; return _
th: parse arg th; return word('th st nd rd', 1+ (th//10)*(th//100%10\==1)*(th//10<4))
/*──────────────────────────────────────────────────────────────────────────────────────*/
primorial: procedure expose @. s. #; parse arg y; != 1 /*obtain the arg Y. */
do p=0 to y; != ! * prime(p) /*calculate product. */
end /*p*/; return ! /*return with the #. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
prime: procedure expose @. s. #; parse arg n; if @.n\==. then return @.n
numeric digits 9 /*limit digs to min.*/
do j=@.#+2 by 2 /*start looking at #*/
if j//2==0 then iterate; if j//3==0 then iterate /*divisible by 2│3 ?*/
parse var j '' -1 _; if _==5 then iterate /*right─most dig≡5? */
if j//7==0 then iterate; if j//11==0 then iterate /*divisible by 7│11?*/
do k=6 while s.k<=j; if j//@.k==0 then iterate j /*divide by primes. */
end /*k*/
#= # + 1; @.#= j; s.#= j * j; return j /*next prime; return*/
end /*j*/

View file

@ -0,0 +1,37 @@
#lang racket
(require (except-in math/number-theory nth-prime))
(define-syntax-rule (define/cache (name arg) body ...)
(begin
(define cache (make-hash))
(define (name arg)
(hash-ref! cache arg (lambda () body ...)))))
(define (num-length n)
;warning: this defines (num-length 0) as 0
(if (zero? n)
0
(add1 (num-length (quotient n 10)))))
(define/cache (nth-prime n)
(if (zero? n)
2
(for/first ([p (in-naturals (add1 (nth-prime (sub1 n))))]
#:when (prime? p))
p)))
(define (primorial n)
(if (zero? n)
1
(* (primorial (sub1 n))
(nth-prime (sub1 n)))))
(displayln
(for/list ([i (in-range 10)])
(primorial i)))
(for ([i (in-range 1 6)])
(printf "Primorial(10^~a) has ~a digits.\n"
i
(num-length (primorial (expt 10 i)))))

View file

@ -0,0 +1,9 @@
use Math::Primesieve;
my $sieve = Math::Primesieve.new;
my @primes = $sieve.primes(10_000_000);
sub primorial($n) { [*] @primes[^$n] }
say "First ten primorials: {(primorial $_ for ^10)}";
say "primorial(10^$_) has {primorial(10**$_).chars} digits" for 1..5;

View file

@ -0,0 +1,11 @@
use Lingua::EN::Numbers;
use ntheory:from<Perl5> <pn_primorial>;
say "First ten primorials: ", ^10 .map( { pn_primorial($_) } ).join: ', ';
for 1..8 {
my $now = now;
printf "primorial(10^%d) has %-11s digits - %s\n", $_,
comma(pn_primorial(10**$_).Str.chars),
"Elapsed seconds: {(now - $now).round: .001}";
}

View file

@ -0,0 +1,55 @@
# Project: Primorial numbers
load "bignumber.ring"
decimals(0)
num = 0
prim = 0
limit = 10000000
see "working..." + nl
see "wait for done..." + nl
while num < 100001
prim = prim + 1
prime = []
primorial(prim)
end
see "done..." + nl
func primorial(pr)
n = 1
n2 = 0
flag = 1
while flag = 1 and n < limit
nr = isPrime(n)
if n=1
nr=1
ok
if nr=1
n2 = n2 + 1
add(prime,n)
ok
if n2=pr
flag=0
num = num + 1
ok
n = n + 1
end
pro = 1
str = ""
for n=1 to len(prime)
pro = FuncMultiply("" + pro,"" + prime[n])
str = str + prime[n] + "*"
next
str = left(str,len(str)-1)
if pr < 11
see "primorial(" + string(pr-1) + ") : " + pro + nl
ok
if pr = 11
see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl
but pr = 101
see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl
but pr = 1001
see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl
but pr = 10001
see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl
but pr = 100001
see "primorial(" + string(pr-1) + ") " + "has " + len(pro) + " digits"+ nl
ok

View file

@ -0,0 +1,12 @@
require 'prime'
def primorial_number(n)
pgen = Prime.each
(1..n).inject(1){|p,_| p*pgen.next}
end
puts "First ten primorials: #{(0..9).map{|n| primorial_number(n)}}"
(1..5).each do |n|
puts "primorial(10**#{n}) has #{primorial_number(10**n).to_s.size} digits"
end

View file

@ -0,0 +1,41 @@
extern crate primal;
extern crate rayon;
extern crate rug;
use rayon::prelude::*;
use rug::Integer;
fn partial(p1 : usize, p2 : usize) -> String {
let mut aux = Integer::from(1);
let (_, hi) = primal::estimate_nth_prime(p2 as u64);
let sieve = primal::Sieve::new(hi as usize);
let prime1 = sieve.nth_prime(p1);
let prime2 = sieve.nth_prime(p2);
for i in sieve.primes_from(prime1).take_while(|i| *i <= prime2) {
aux = Integer::from(aux * i as u32);
}
aux.to_string_radix(10)
}
fn main() {
let mut j1 = Integer::new();
for k in [2,3,5,7,11,13,17,19,23,29].iter() {
j1.assign_primorial(*k);
println!("Primorial : {}", j1);
}
println!("Digits of primorial 10 : {}", partial(1, 10).chars().fold(0, |n, _| n + 1));
println!("Digits of primorial 100 : {}", partial(1, 100).chars().fold(0, |n, _| n + 1));
println!("Digits of primorial 1_000 : {}", partial(1, 1_000).chars().fold(0, |n, _| n + 1));
println!("Digits of primorial 10_000 : {}", partial(1, 10_000).chars().fold(0, |n, _| n + 1));
println!("Digits of primorial 100_000 : {}", partial(1, 100_000).chars().fold(0, |n, _| n + 1));
let mut auxi = Integer::from(1);
let ranges = vec![[1, 300_000], [300_001, 550_000], [550_001, 800_000], [800_001, 1_000_000]];
let v = ranges.par_iter().map(|value| partial(value[0], value[1])).collect::<Vec<_>>();
for i in v.iter() {
auxi =Integer::from(&auxi * i.parse::<Integer>().unwrap());
}
let result = auxi.to_string_radix(10).chars().fold(0, |n, _| n+1);
println!("Digits of primorial 1_000_000 : {}",result);
}

View file

@ -0,0 +1,19 @@
import spire.math.SafeLong
import spire.implicits._
import scala.collection.parallel.immutable.ParVector
object Primorial {
def main(args: Array[String]): Unit = {
println(
s"""|First 10 Primorials:
|${LazyList.range(0, 10).map(n => f"$n: ${primorial(n).toBigInt}%,d").mkString("\n")}
|
|Lengths of Primorials:
|${LazyList.range(1, 7).map(math.pow(10, _).toInt).map(i => f"$i%,d: ${primorial(i).toString.length}%,d").mkString("\n")}
|""".stripMargin)
}
def primorial(num: Int): SafeLong = if(num == 0) 1 else primesSL.take(num).to(ParVector).reduce(_*_)
lazy val primesSL: Vector[SafeLong] = 2 +: ParVector.range(3, 20000000, 2).filter(n => !Iterator.range(3, math.sqrt(n).toInt + 1, 2).exists(n%_ == 0)).toVector.sorted.map(SafeLong(_))
}

View file

@ -0,0 +1,8 @@
say (
'First ten primorials: ',
{|i| pn_primorial(i) }.map(^10).join(', ')
)
{ |i|
say ("primorial(10^#{i}) has " + pn_primorial(10**i).len + ' digits')
} << 1..6

View file

@ -0,0 +1,33 @@
import "/big" for BigInt
import "/math" for Int
import "/fmt" for Fmt
var vecprod = Fn.new { |primes|
var le = primes.count
if (le == 0) return BigInt.one
var s = List.filled(le, null)
for (i in 0...le) s[i] = BigInt.new(primes[i])
while (le > 1) {
var c = (le/2).floor
for(i in 0...c) s[i] = s[i] * s[le-i-1]
if (le & 1 == 1) c = c + 1
le = c
}
return s[0]
}
var primes = Int.primeSieve(1.3e6) // enough to generate first 100,000 primes
var prod = 1
System.print("The first ten primorial numbers are:")
for (i in 0..9) {
System.print("%(i): %(prod)")
prod = prod * primes[i]
}
System.print("\nThe following primorials have the lengths shown:")
// first multiply the first 100,000 primes together in pairs to reduce BigInt conversions needed
var primes2 = List.filled(50000, 0)
for (i in 0...50000) primes2[i] = primes[2*i] * primes[2*i+1]
for (i in [10, 100, 1000, 10000, 100000]) {
Fmt.print("$6d: $d", i, vecprod.call(primes2[0...i/2]).toString.count)
}

View file

@ -0,0 +1,15 @@
import "./math" for Int
import "./gmp" for Mpz
import "./fmt" for Fmt
var limit = 16 * 1e6 // more than enough to find first million primes
var primes = Int.primeSieve(limit-1)
primes.insert(0, 1)
System.print("The first ten primorial numbers are:")
var z = Mpz.new()
for (i in 0..9) System.print("%(i): %(z.primorial(primes[i]))")
System.print("\nThe following primorials have the lengths shown:")
for (i in [1e1, 1e2, 1e3, 1e4, 1e5, 1e6]) {
Fmt.print("$7d: $d", i, z.primorial(primes[i]).digitsInBase(10))
}

View file

@ -0,0 +1,11 @@
sieve:=Import("sieve.zkl",False,False,False).postponed_sieve;
primes:=Utils.Generator(sieve).walk(0d10); // first 10 primes
foreach n in (10)
{ primes[0,n].reduce('*,1):println("primorial(%d)=%d".fmt(n,_)); }
var [const] BN=Import("zklBigNum");
primes:=Utils.Generator(sieve).walk(0d1_000_000);
foreach n in ([1..6]){ n=(10).pow(n);
primes[0,n].pump(BN(1).mul)
:println("primorial(%,d)=%,d digits".fmt(n,_.numDigits));
}