primorial.frink

Download or view primorial.frink in plain text format


/** This program calculates primorial numbers.  A primorial is the product
    of primes.

    primorial[0] = 1 (by definition)
    primorial[1] = 2
    primorial[2] = 6
    primorial[3] = 30

    This does not do any caching of results.
*/

primorial[n] := product[first[primes[], n]]

/** This is a recursive algorithm that splits the results into an upper and
    lower half and multiplies in stages.  This is much faster for large
    numbers. */

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
}

/** Rosetta code tests.

    https://rosettacode.org/wiki/Primorial_numbers
*/


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."]


Download or view primorial.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 19966 days, 7 hours, 30 minutes ago.