tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
47
Task/Prime-decomposition/Python/prime-decomposition-1.py
Normal file
47
Task/Prime-decomposition/Python/prime-decomposition-1.py
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import sys
|
||||
|
||||
def is_prime(n):
|
||||
return zip((True, False), decompose(n))[-1][0]
|
||||
|
||||
class IsPrimeCached(dict):
|
||||
def __missing__(self, n):
|
||||
r = is_prime(n)
|
||||
self[n] = r
|
||||
return r
|
||||
|
||||
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 decompose(n):
|
||||
for p in primes():
|
||||
if p*p > n: break
|
||||
while n % p == 0:
|
||||
yield p
|
||||
n /=p
|
||||
if n > 1:
|
||||
yield n
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Example: calculate factors of Mersenne numbers to M59 #
|
||||
|
||||
import time
|
||||
|
||||
for m in primes():
|
||||
p = 2 ** m - 1
|
||||
print( "2**{0:d}-1 = {0:d}, with factors:".format(m, p) )
|
||||
start = time.time()
|
||||
for factor in decompose(p):
|
||||
print factor,
|
||||
sys.stdout.flush()
|
||||
|
||||
print( "=> {0:.2f}s".format( time.time()-start ) )
|
||||
if m >= 59:
|
||||
break
|
||||
18
Task/Prime-decomposition/Python/prime-decomposition-2.py
Normal file
18
Task/Prime-decomposition/Python/prime-decomposition-2.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
primelist = [2,3]
|
||||
def is_prime(n):
|
||||
for y in primes():
|
||||
if not n % y: return False
|
||||
if n > y * y: return True
|
||||
|
||||
def primes():
|
||||
for n in primelist: yield n
|
||||
|
||||
n = primelist[-1] + 2
|
||||
while True:
|
||||
n += 2
|
||||
for x in primelist:
|
||||
if not n % x: break
|
||||
if x * x > n:
|
||||
primelist.append(n)
|
||||
yield n
|
||||
break
|
||||
21
Task/Prime-decomposition/Python/prime-decomposition-3.py
Normal file
21
Task/Prime-decomposition/Python/prime-decomposition-3.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
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)
|
||||
Loading…
Add table
Add a link
Reference in a new issue