March 2014 update
This commit is contained in:
parent
09687c4926
commit
a25938f123
1846 changed files with 21876 additions and 5203 deletions
13
Task/Prime-decomposition/Ada/prime-decomposition-1.ada
Normal file
13
Task/Prime-decomposition/Ada/prime-decomposition-1.ada
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
generic
|
||||
type Number is private;
|
||||
Zero : Number;
|
||||
One : Number;
|
||||
Two : Number;
|
||||
with function "+" (X, Y : Number) return Number is <>;
|
||||
with function "/" (X, Y : Number) return Number is <>;
|
||||
with function "mod" (X, Y : Number) return Number is <>;
|
||||
with function ">=" (X, Y : Number) return Boolean is <>;
|
||||
package Prime_Numbers is
|
||||
type Number_List is array (Positive range <>) of Number;
|
||||
function Decompose (N : Number) return Number_List;
|
||||
end Prime_Numbers;
|
||||
30
Task/Prime-decomposition/Ada/prime-decomposition-2.ada
Normal file
30
Task/Prime-decomposition/Ada/prime-decomposition-2.ada
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
package body Prime_Numbers is
|
||||
function Decompose (N : Number) return Number_List is
|
||||
Size : Natural := 0;
|
||||
M : Number := N;
|
||||
K : Number := Two;
|
||||
begin
|
||||
-- Estimation of the result length from above
|
||||
while M >= Two loop
|
||||
M := (M + One) / Two;
|
||||
Size := Size + 1;
|
||||
end loop;
|
||||
M := N;
|
||||
-- Filling the result with prime numbers
|
||||
declare
|
||||
Result : Number_List (1..Size);
|
||||
Index : Positive := 1;
|
||||
begin
|
||||
while N >= K loop -- Divisors loop
|
||||
while Zero = (M mod K) loop -- While divides
|
||||
Result (Index) := K;
|
||||
Index := Index + 1;
|
||||
M := M / K;
|
||||
end loop;
|
||||
K := K + One;
|
||||
end loop;
|
||||
return Result (1..Index - 1);
|
||||
end;
|
||||
end Decompose;
|
||||
|
||||
end Prime_Numbers;
|
||||
18
Task/Prime-decomposition/Ada/prime-decomposition-3.ada
Normal file
18
Task/Prime-decomposition/Ada/prime-decomposition-3.ada
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
with Prime_Numbers, Ada.Text_IO;
|
||||
|
||||
procedure Test_Prime is
|
||||
|
||||
package Integer_Numbers is new
|
||||
Prime_Numbers (Natural, 0, 1, 2);
|
||||
use Integer_Numbers;
|
||||
|
||||
procedure Put (List : Number_List) is
|
||||
begin
|
||||
for Index in List'Range loop
|
||||
Ada.Text_IO.Put (Positive'Image (List (Index)));
|
||||
end loop;
|
||||
end Put;
|
||||
|
||||
begin
|
||||
Put (Decompose (12));
|
||||
end Test_Prime;
|
||||
|
|
@ -1,60 +0,0 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
|
||||
procedure Test_Prime is
|
||||
generic
|
||||
type Number is private;
|
||||
Zero : Number;
|
||||
One : Number;
|
||||
Two : Number;
|
||||
with function Image (X : Number) return String is <>;
|
||||
with function "+" (X, Y : Number) return Number is <>;
|
||||
with function "/" (X, Y : Number) return Number is <>;
|
||||
with function "mod" (X, Y : Number) return Number is <>;
|
||||
with function ">=" (X, Y : Number) return Boolean is <>;
|
||||
package Prime_Numbers is
|
||||
type Number_List is array (Positive range <>) of Number;
|
||||
function Decompose (N : Number) return Number_List;
|
||||
procedure Put (List : Number_List);
|
||||
end Prime_Numbers;
|
||||
|
||||
package body Prime_Numbers is
|
||||
function Decompose (N : Number) return Number_List is
|
||||
Size : Natural := 0;
|
||||
M : Number := N;
|
||||
K : Number := Two;
|
||||
begin
|
||||
-- Estimation of the result length from above
|
||||
while M >= Two loop
|
||||
M := (M + One) / Two;
|
||||
Size := Size + 1;
|
||||
end loop;
|
||||
M := N;
|
||||
-- Filling the result with prime numbers
|
||||
declare
|
||||
Result : Number_List (1..Size);
|
||||
Index : Positive := 1;
|
||||
begin
|
||||
while N >= K loop -- Divisors loop
|
||||
while Zero = (M mod K) loop -- While divides
|
||||
Result (Index) := K;
|
||||
Index := Index + 1;
|
||||
M := M / K;
|
||||
end loop;
|
||||
K := K + One;
|
||||
end loop;
|
||||
return Result (1..Index - 1);
|
||||
end;
|
||||
end Decompose;
|
||||
|
||||
procedure Put (List : Number_List) is
|
||||
begin
|
||||
for Index in List'Range loop
|
||||
Put (Image (List (Index)));
|
||||
end loop;
|
||||
end Put;
|
||||
end Prime_Numbers;
|
||||
package Integer_Numbers is new Prime_Numbers (Natural, 0, 1, 2, Positive'Image);
|
||||
use Integer_Numbers;
|
||||
begin
|
||||
Put (Decompose (12));
|
||||
end Test_Prime;
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
;;; Tail-recursive version
|
||||
(defun factor (n &optional (acc '()))
|
||||
(when (> n 1) (loop with max-d = (isqrt n)
|
||||
for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do
|
||||
(cond ((> d max-d) (return (cons (list n 1) acc)))
|
||||
((zerop (rem n d))
|
||||
(return (factor (truncate n d) (if (eq d (caar acc))
|
||||
(cons
|
||||
(list (caar acc) (1+ (cadar acc)))
|
||||
(cdr acc))
|
||||
(cons (list d 1) acc)))))))))
|
||||
|
|
@ -1,23 +1,17 @@
|
|||
import std.stdio, std.bigint, std.algorithm, std.traits;
|
||||
import std.stdio, std.bigint, std.algorithm, std.traits, std.range;
|
||||
|
||||
Unqual!T[] decompose(T)(in T number) pure /*nothrow*/
|
||||
in {
|
||||
assert(number > 1);
|
||||
} body {
|
||||
alias UT = Unqual!T;
|
||||
typeof(return) result;
|
||||
UT n = number;
|
||||
Unqual!T n = number;
|
||||
|
||||
for (UT i = 2; n % i == 0;) {
|
||||
for (Unqual!T i = 2; n % i == 0; n /= i)
|
||||
result ~= i;
|
||||
n /= i;
|
||||
}
|
||||
for (UT i = 3; n >= i * i; i += 2) {
|
||||
while (n % i == 0) {
|
||||
for (Unqual!T i = 3; n >= i * i; i += 2)
|
||||
for (; n % i == 0; n /= i)
|
||||
result ~= i;
|
||||
n /= i;
|
||||
}
|
||||
}
|
||||
|
||||
if (n != 1)
|
||||
result ~= n;
|
||||
|
|
@ -25,9 +19,7 @@ in {
|
|||
}
|
||||
|
||||
void main() {
|
||||
foreach (immutable n; 2 .. 10)
|
||||
n.decompose.writeln;
|
||||
|
||||
writefln("%(%s\n%)", iota(2, 10).map!decompose);
|
||||
decompose(1023 * 1024).writeln;
|
||||
BigInt(2 * 3 * 5 * 7 * 11 * 11 * 13 * 17).decompose.writeln;
|
||||
decompose(16860167264933UL.BigInt * 179951).writeln;
|
||||
|
|
|
|||
|
|
@ -1,11 +1,43 @@
|
|||
public static List<BigInteger> primeFactorBig(BigInteger a){
|
||||
List<BigInteger> ans = new LinkedList<BigInteger>();
|
||||
private static final BigInteger TWO = BigInteger.valueOf(2);
|
||||
private static final BigInteger THREE = BigInteger.valueOf(3);
|
||||
private static final BigInteger FIVE = BigInteger.valueOf(5);
|
||||
|
||||
for(BigInteger divisor = BigInteger.valueOf(2);
|
||||
a.compareTo(ONE) > 0; divisor = divisor.add(ONE))
|
||||
while(a.mod(divisor).equals(ZERO)){
|
||||
ans.add(divisor);
|
||||
a = a.divide(divisor);
|
||||
public static ArrayList<BigInteger> primeDecomp(BigInteger n){
|
||||
if(n.compareTo(TWO) < 0) return null;
|
||||
ArrayList<BigInteger> factors = new ArrayList<BigInteger>();
|
||||
|
||||
// handle even values
|
||||
while(n.and(BigInteger.ONE).equals(BigInteger.ZERO)){
|
||||
n = n.shiftRight(1);
|
||||
factors.add(TWO);
|
||||
}
|
||||
|
||||
// handle values divisible by three
|
||||
while(n.mod(THREE).equals(BigInteger.ZERO)){
|
||||
factors.add(THREE);
|
||||
n = n.divide(THREE);
|
||||
}
|
||||
|
||||
// handle values divisible by five
|
||||
while(n.mod(FIVE).equals(BigInteger.ZERO)){
|
||||
factors.add(FIVE);
|
||||
n = n.divide(FIVE);
|
||||
}
|
||||
|
||||
// much like how we can skip multiples of two, we can also skip
|
||||
// multiples of three and multiples of five. This increment array
|
||||
// helps us to accomplish that
|
||||
int[] pattern = {4,2,4,2,4,6,2,6};
|
||||
int pattern_index = 0;
|
||||
BigInteger current_test = BigInteger.valueOf(7);
|
||||
while(!n.equals(BigInteger.ONE)){
|
||||
while(n.mod(current_test).equals(BigInteger.ZERO)){
|
||||
factors.add(current_test);
|
||||
n = n.divide(current_test);
|
||||
}
|
||||
return ans;
|
||||
current_test = current_test.add(BigInteger.valueOf(pattern[pattern_index]));
|
||||
pattern_index = (pattern_index + 1) & 7;
|
||||
}
|
||||
|
||||
return factors;
|
||||
}
|
||||
|
|
|
|||
11
Task/Prime-decomposition/Java/prime-decomposition-5.java
Normal file
11
Task/Prime-decomposition/Java/prime-decomposition-5.java
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
public static List<BigInteger> primeFactorBig(BigInteger a){
|
||||
List<BigInteger> ans = new LinkedList<BigInteger>();
|
||||
|
||||
for(BigInteger divisor = BigInteger.valueOf(2);
|
||||
a.compareTo(ONE) > 0; divisor = divisor.add(ONE))
|
||||
while(a.mod(divisor).equals(ZERO)){
|
||||
ans.add(divisor);
|
||||
a = a.divide(divisor);
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
> ifactor(1337);
|
||||
(7) (191)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
> ifactors(1337);
|
||||
[1, [[7, 1], [191, 1]]]
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
prime_dec(n) := flatten(create_list(makelist(a[1], a[2]), a, ifactors(n)))$
|
||||
prime_dec(n) := flatten(create_list(makelist(first(a), second(a)), a, ifactors(n)))$
|
||||
|
||||
/* or, slighlty more "functional" */
|
||||
prime_dec(n) := flatten(map(lambda([a], apply(makelist, a)), ifactors(n)))$
|
||||
|
|
|
|||
|
|
@ -1,7 +1,18 @@
|
|||
from __future__ import print_function
|
||||
|
||||
import sys
|
||||
from itertools import islice, cycle, count
|
||||
|
||||
try:
|
||||
from itertools import compress
|
||||
except ImportError:
|
||||
def compress(data, selectors):
|
||||
"""compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"""
|
||||
return (d for d, s in zip(data, selectors) if s)
|
||||
|
||||
|
||||
def is_prime(n):
|
||||
return zip((True, False), decompose(n))[-1][0]
|
||||
return list(zip((True, False), decompose(n)))[-1][0]
|
||||
|
||||
class IsPrimeCached(dict):
|
||||
def __missing__(self, n):
|
||||
|
|
@ -11,24 +22,54 @@ class IsPrimeCached(dict):
|
|||
|
||||
is_prime_cached = IsPrimeCached()
|
||||
|
||||
def primes():
|
||||
yield 2
|
||||
n = 3
|
||||
while n < sys.maxint - 2:
|
||||
yield n
|
||||
n += 2
|
||||
while n < sys.maxint - 2 and not is_prime_cached[n]:
|
||||
n += 2
|
||||
def croft():
|
||||
"""Yield prime integers using the Croft Spiral sieve.
|
||||
|
||||
This is a variant of wheel factorisation modulo 30.
|
||||
"""
|
||||
# Copied from:
|
||||
# https://code.google.com/p/pyprimes/source/browse/src/pyprimes.py
|
||||
# Implementation is based on erat3 from here:
|
||||
# http://stackoverflow.com/q/2211990
|
||||
# and this website:
|
||||
# http://www.primesdemystified.com/
|
||||
# Memory usage increases roughly linearly with the number of primes seen.
|
||||
# dict ``roots`` stores an entry x:p for every prime p.
|
||||
for p in (2, 3, 5):
|
||||
yield p
|
||||
roots = {9: 3, 25: 5} # Map d**2 -> d.
|
||||
primeroots = frozenset((1, 7, 11, 13, 17, 19, 23, 29))
|
||||
selectors = (1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0)
|
||||
for q in compress(
|
||||
# Iterate over prime candidates 7, 9, 11, 13, ...
|
||||
islice(count(7), 0, None, 2),
|
||||
# Mask out those that can't possibly be prime.
|
||||
cycle(selectors)
|
||||
):
|
||||
# Using dict membership testing instead of pop gives a
|
||||
# 5-10% speedup over the first three million primes.
|
||||
if q in roots:
|
||||
p = roots[q]
|
||||
del roots[q]
|
||||
x = q + 2*p
|
||||
while x in roots or (x % 30) not in primeroots:
|
||||
x += 2*p
|
||||
roots[x] = p
|
||||
else:
|
||||
roots[q*q] = q
|
||||
yield q
|
||||
primes = croft
|
||||
|
||||
def decompose(n):
|
||||
for p in primes():
|
||||
if p*p > n: break
|
||||
while n % p == 0:
|
||||
yield p
|
||||
n /=p
|
||||
n //=p
|
||||
if n > 1:
|
||||
yield n
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Example: calculate factors of Mersenne numbers to M59 #
|
||||
|
||||
|
|
@ -36,10 +77,10 @@ if __name__ == '__main__':
|
|||
|
||||
for m in primes():
|
||||
p = 2 ** m - 1
|
||||
print( "2**{0:d}-1 = {0:d}, with factors:".format(m, p) )
|
||||
print( "2**{0:d}-1 = {1:d}, with factors:".format(m, p) )
|
||||
start = time.time()
|
||||
for factor in decompose(p):
|
||||
print factor,
|
||||
print(factor, end=' ')
|
||||
sys.stdout.flush()
|
||||
|
||||
print( "=> {0:.2f}s".format( time.time()-start ) )
|
||||
|
|
|
|||
|
|
@ -1,21 +1,27 @@
|
|||
primelist = [2, 3]
|
||||
def is_prime(n):
|
||||
if n in primelist: return True
|
||||
if n < primelist[-1]: return False
|
||||
from math import floor, sqrt
|
||||
try:
|
||||
long
|
||||
except NameError:
|
||||
long = int
|
||||
|
||||
for y in primes():
|
||||
if not n % y: return False
|
||||
if n < y * y: return True
|
||||
def fac(n):
|
||||
step = lambda x: 1 + x*4 - (x//2)*2
|
||||
maxq = long(floor(sqrt(n)))
|
||||
d = 1
|
||||
q = n % 2 == 0 and 2 or 3
|
||||
while q <= maxq and n % q != 0:
|
||||
q = step(d)
|
||||
d += 1
|
||||
res = []
|
||||
if q <= maxq:
|
||||
res.extend(fac(n//q))
|
||||
res.extend(fac(q))
|
||||
else: res=[n]
|
||||
return res
|
||||
|
||||
def primes():
|
||||
for n in primelist: yield n
|
||||
|
||||
n = primelist[-1]
|
||||
while True:
|
||||
n += 2
|
||||
for x in primelist:
|
||||
if not n % x: break
|
||||
if x * x > n:
|
||||
primelist.append(n)
|
||||
yield n
|
||||
break
|
||||
if __name__ == '__main__':
|
||||
import time
|
||||
start = time.time()
|
||||
tocalc = 2**59-1
|
||||
print("%s = %s" % (tocalc, fac(tocalc)))
|
||||
print("Needed %ss" % (time.time() - start))
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
irb(main):001:0> require 'mathn'
|
||||
irb(main):001:0> require 'prime'
|
||||
=> true
|
||||
irb(main):002:0> 2131447995319.prime_division
|
||||
=> [[701, 1], [1123, 2], [2411, 1]]
|
||||
irb(main):003:0> 2543821448263974486045199.prime_division
|
||||
=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,13 @@
|
|||
irb(main):001:0> require 'prime'
|
||||
=> true
|
||||
irb(main):003:0> 2543821448263974486045199.prime_division
|
||||
=> [[701, 1], [1123, 2], [2411, 1], [1092461, 2]]
|
||||
# Get prime decomposition of integer _i_.
|
||||
# This routine is terribly inefficient, but elegance rules.
|
||||
def prime_factors(i)
|
||||
v = (2..i-1).detect{|j| i % j == 0}
|
||||
v ? ([v] + prime_factors(i/v)) : [i]
|
||||
end
|
||||
|
||||
# Example: Decompose all possible Mersenne primes up to 2**31-1.
|
||||
# This may take several minutes to show that 2**31-1 is prime.
|
||||
(2..31).each do |i|
|
||||
factors = prime_factors(2**i-1)
|
||||
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
|
||||
end
|
||||
|
|
|
|||
|
|
@ -1,13 +1,32 @@
|
|||
# Get prime decomposition of integer _i_.
|
||||
# This routine is terribly inefficient, but elegance rules.
|
||||
def prime_factors(i)
|
||||
v = (2..i-1).detect{|j| i % j == 0}
|
||||
v ? ([v] + prime_factors(i/v)) : [i]
|
||||
# This routine is more efficient than prime_factors,
|
||||
# and quite similar to Integer#prime_division of MRI 1.9.
|
||||
def prime_factors_faster(i)
|
||||
factors = []
|
||||
check = proc do |p|
|
||||
while(q, r = i.divmod(p)
|
||||
r.zero?)
|
||||
factors << p
|
||||
i = q
|
||||
end
|
||||
end
|
||||
check[2]
|
||||
check[3]
|
||||
p = 5
|
||||
while p * p <= i
|
||||
check[p]
|
||||
p += 2
|
||||
check[p]
|
||||
p += 4 # skip multiples of 2 and 3
|
||||
end
|
||||
factors << i if i > 1
|
||||
factors
|
||||
end
|
||||
|
||||
# Example: Decompose all possible Mersenne primes up to 2**31-1.
|
||||
# This may take several minutes to show that 2**31-1 is prime.
|
||||
(2..31).each do |i|
|
||||
factors = prime_factors(2**i-1)
|
||||
# Example: Decompose all possible Mersenne primes up to 2**70-1.
|
||||
# This may take several minutes to show that 2**61-1 is prime,
|
||||
# but 2**62-1 and 2**67-1 are not prime.
|
||||
(2..70).each do |i|
|
||||
factors = prime_factors_faster(2**i-1)
|
||||
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
|
||||
end
|
||||
|
|
|
|||
|
|
@ -1,32 +1,10 @@
|
|||
# Get prime decomposition of integer _i_.
|
||||
# This routine is more efficient than prime_factors,
|
||||
# and quite similar to Integer#prime_division of MRI 1.9.
|
||||
def prime_factors_faster(i)
|
||||
factors = []
|
||||
check = proc do |p|
|
||||
while(q, r = i.divmod(p)
|
||||
r.zero?)
|
||||
factors << p
|
||||
i = q
|
||||
end
|
||||
require 'benchmark'
|
||||
require 'mathn'
|
||||
Benchmark.bm(24) do |x|
|
||||
[2**25 - 6, 2**35 - 7].each do |i|
|
||||
puts "#{i} = #{prime_factors_faster(i).join(' * ')}"
|
||||
x.report(" prime_factors") { prime_factors(i) }
|
||||
x.report(" prime_factors_faster") { prime_factors_faster(i) }
|
||||
x.report(" Integer#prime_division") { i.prime_division }
|
||||
end
|
||||
check[2]
|
||||
check[3]
|
||||
p = 5
|
||||
while p * p <= i
|
||||
check[p]
|
||||
p += 2
|
||||
check[p]
|
||||
p += 4 # skip multiples of 2 and 3
|
||||
end
|
||||
factors << i if i > 1
|
||||
factors
|
||||
end
|
||||
|
||||
# Example: Decompose all possible Mersenne primes up to 2**70-1.
|
||||
# This may take several minutes to show that 2**61-1 is prime,
|
||||
# but 2**62-1 and 2**67-1 are not prime.
|
||||
(2..70).each do |i|
|
||||
factors = prime_factors_faster(2**i-1)
|
||||
puts "2**#{i}-1 = #{2**i-1} = #{factors.join(' * ')}"
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue