September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -21,7 +21,12 @@ Note: The program must not be limited by the word size of your computer or some
;Related tasks:
*   [[Factors of an integer]]
*   [[Primality by trial division]]
*   [[count in factors]]
*   [[factors of an integer]]
*   [[Sieve of Eratosthenes]]
*   [[primality by trial division]]
*   [[factors of a Mersenne number]]
*   [[trial factoring of a Mersenne number]]
*   [[partition an integer X into N primes]]
*   [[sequence of primes by Trial Division]]
<br><br>

View file

@ -0,0 +1,25 @@
@echo off
::usage: cmd /k primefactor.cmd number
setlocal enabledelayedexpansion
set /a compo=%1
if "%compo%"=="" goto:eof
set list=%compo%= (
set /a div=2 & call :loopdiv
set /a div=3 & call :loopdiv
set /a div=5,inc=2
:looptest
call :loopdiv
set /a div+=inc,inc=6-inc,div2=div*div
if %div2% lss %compo% goto looptest
if %compo% neq 1 set list= %list% %compo%
echo %list%) & goto:eof
:loopdiv
set /a "res=compo%%div
if %res% neq 0 goto:eof
set list=%list% %div%,
set/a compo/=div
goto:loopdiv

View file

@ -1,2 +1,3 @@
julia> Pkg.add("Primes")
julia> factor(8796093022207)
[9719=>1,431=>1,2099863=>1]

View file

@ -0,0 +1,35 @@
// version 1.0.6
import java.math.BigInteger
val bigTwo = BigInteger.valueOf(2L)
val bigThree = BigInteger.valueOf(3L)
fun getPrimeFactors(n: BigInteger): MutableList<BigInteger> {
val factors = mutableListOf<BigInteger>()
if (n < bigTwo) return factors
if (n.isProbablePrime(20)) {
factors.add(n)
return factors
}
var factor = bigTwo
var nn = n
while (true) {
if (nn % factor == BigInteger.ZERO) {
factors.add(factor)
nn /= factor
if (nn == BigInteger.ONE) return factors
if (nn.isProbablePrime(20)) factor = nn
}
else if (factor >= bigThree) factor += bigTwo
else factor = bigThree
}
}
fun main(args: Array<String>) {
val primes = intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
for (prime in primes) {
val bigPow2 = bigTwo.pow(prime) - BigInteger.ONE
println("2^${"%2d".format(prime)} - 1 = ${bigPow2.toString().padEnd(30)} => ${getPrimeFactors(bigPow2)}")
}
}

View file

@ -1,47 +0,0 @@
import strutils, math, sequtils, times
proc getStep(n: int64) : int64 {.inline.} =
result = 1 + n*4 - int64(n /% 2)*2
proc primeFac(n: int64): seq[int64] =
var res: seq[int64] = @[]
var maxq = int64(floor(sqrt(float(n))))
var d = 1
var q: int64 = (n %% 2) and 2 or 3 # either 2 or 3, alternating
while (q <= maxq) and ((n %% q) != 0):
q = getStep(d)
d += 1
if q <= maxq:
var q1: seq[int64] = primeFac(n /% q)
var q2: seq[int64] = primeFac(q)
res = concat(q2, q1, res)
else:
res.add(n)
result = res
var is_prime: seq[Bool] = @[]
is_prime.add(False)
is_prime.add(False)
iterator primes(limit: int): int =
for n in high(is_prime) .. limit+2: is_prime.add(True)
for n in 2 .. limit + 1:
if is_prime[n]:
yield n
for i in countup((n *% n), limit+1, n): # start at ``n`` squared
try:
is_prime[i] = False
except EInvalidIndex: break
# Example: calculate factors of Mersenne numbers to M59 #
for m in primes(59):
var p = int64(pow(2.0,float(m)) - 1)
write(stdout,"2**$1-1 = $2, with factors: " % [$m, $p] )
var start = cpuTime()
var f = primeFac(p)
for factor in f:
write(stdout, factor)
write(stdout, ", ")
FlushFile(stdout)
writeln(stdout, "=> $#ms" % $int(1000*(cpuTime()-start)) )

View file

@ -0,0 +1,31 @@
atom t0 = time()
include builtins\bigatom.e
constant zero = ba_new(0)
function ba_factorise(bigatom n)
sequence res = {}
bigatom p = ba_new(2),
lim = ba_floor(ba_sqrt(n))
integer step = 1
while ba_compare(p,lim)<=0 do
while ba_remainder(n,p)=zero do
res = append(res,ba_sprint(p))
n = ba_divide(n,p)
if ba_compare(n,p)=0 then exit end if
lim = ba_floor(ba_sqrt(n))
end while
p = ba_add(p,step)
step = 2
end while
res = append(res,ba_sprint(n))
return res
end function
sequence primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47}--,53,59}
for i=1 to length(primes) do
?ba_factorise(ba_sub(ba_power(2,primes[i]),1))
end for
?ba_factorise(ba_new("600851475143"))
?time()-t0

View file

@ -1,21 +0,0 @@
def fac(n):
step = lambda x: 1 + x*4 - (x/2)*2
maxq = long(math.floor(math.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
if __name__ == '__main__':
import time
start = time.time()
tocalc = 2**59-1
print "%s = %s" % (tocalc, fac(tocalc))
print "Needed %ss" % (time.time() - start)

View file

@ -1,10 +0,0 @@
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
end

View file

@ -1,11 +0,0 @@
// A test
decompose(423) // Results: List(3,3,47)
decompose(423).product // Results: 423
// A BigInt test
decompose(BigInt("2535301200456458802993406410752"))
// Results: a list of (2)s
decompose(BigInt("2535301200456458802993406410752")).length
// Results: 101
decompose(BigInt("2535301200456458802993406410752")).product
// Results: 2535301200456458802993406410752

View file

@ -1,93 +1,16 @@
namespace eval primes {}
proc primes::reset {} {
variable list [list]
variable current_index end
}
namespace eval primes {reset}
proc primes::restart {} {
variable list
variable current_index
if {[llength $list] > 0} {
set current_index 0
}
}
proc primes::is_prime {candidate} {
variable list
if {$candidate in $list} {return true}
foreach prime $list {
if {$candidate % $prime == 0} {
return false
}
if {$prime * $prime > $candidate} {
return true
}
}
while true {
set largest [get_next_prime]
if {$largest * $largest >= $candidate} {
return [is_prime $candidate]
}
}
}
proc primes::get_next_prime {} {
variable list
variable current_index
if {$current_index ne "end"} {
set p [lindex $list $current_index]
if {[incr current_index] == [llength $list]} {
set current_index end
}
return $p
}
switch -exact -- [llength $list] {
0 {set candidate 2}
1 {set candidate 3}
default {
set candidate [lindex $list end]
while true {
incr candidate 2
if {[is_prime $candidate]} break
}
}
}
lappend list $candidate
return $candidate
}
# return the prime factors of a number in a dictionary.
# The keys will be the factors, the value will be the number
# of times the factor divides the given number
#
# example: 120 = 2**3 * 3 * 5, so
# [primes::factors 120] returns 2 3 3 1 5 1
# so: set prod 1
# dict for {p e} [primes::factors 120] {
# set prod [expr {$prod * $p**$e}]
# }
# expr {$prod == 120} ;# ==> true
#
proc primes::factors {num} {
restart
set factors [dict create]
for {set i [get_next_prime]} {$i <= $num} {} {
if {$num % $i == 0} {
dict incr factors $i
set num [expr {$num / $i}]
continue
} elseif {$i*$i > $num} {
dict incr factors $num
break
} else {
set i [get_next_prime]
}
}
return $factors
proc factors {x} {
# list the prime factors of x in ascending order
set result [list]
while {$x % 2 == 0} {
lappend result 2
set x [expr {$x / 2}]
}
for {set i 3} {$i*$i <= $x} {incr i 2} {
while {$x % $i == 0} {
lappend result $i
set x [expr {$x / $i}]
}
}
if {$x != 1} {lappend result $x}
return $result
}

View file

@ -1,8 +1,5 @@
primes::reset
foreach m {2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59} {
set n [expr {2**$m - 1}]
catch {time {set f [dict create {*}[primes::factors $n]]} 1} tm
set primes [list]
dict for {p e} $f {lappend primes {*}[lrepeat $e $p]}
catch {time {set primes [factors $n]} 1} tm
puts [format "2**%02d-1 = %-18s = %-22s => %s" $m $n [join $primes *] $tm]
}

View file

@ -0,0 +1,13 @@
fcn primeFactors(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
else{
q,r:=n.divr(k); // divr-->(quotient,remainder)
if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
return(self.fcn(n,k+1+k.isOdd,acc,maxD))
}
}(n,2,Sink(List),n.toFloat().sqrt());
m:=acc.reduce('*,1); // mulitply factors
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}

View file

@ -0,0 +1,4 @@
foreach n in (T(5,12, 2147483648, 2199023255551, 8796093022207,
9007199254740991, 576460752303423487)){
println(n,": ",primeFactors(n).concat(", "))
}

View file

@ -0,0 +1,13 @@
fcn factorsBI(n){ // Return a list of factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
else{
q,r:=n.div2(k); // divr-->(quotient,remainder)
if(r==0) return(self.fcn(q,k,acc.write(k),q.root(2)));
return(self.fcn(n,k+1+k.isOdd,acc,maxD))
}
}(n,2,Sink(List),n.root(2));
m:=acc.reduce('*,BN(1)); // mulitply factors
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
}

View file

@ -0,0 +1,5 @@
var BN=Import("zklBigNum");
foreach n in (T(BN("12"),
BN("340282366920938463463374607431768211455"))){
println(n,": ",factorsBI(n).concat(", "))
}