-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
63 lines (54 loc) · 1.53 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import os
import itertools
import numpy as np
beep = lambda x: os.system("echo -n '\a';sleep 0.2;" * x)
def is_palindrome(a: int) -> bool:
return str(a) == str(a)[::-1]
def is_binary_palindrome(a: int) -> bool:
s = "{0:b}".format(a)
return s == s[::-1]
def divisors(nb):
divisors = []
inf = 2
for i in range(inf, int(nb**0.5)+1):
q, r = divmod(nb, i)
if r == 0:
if q >= i:
divisors.append(i)
if q > i:
divisors.append(nb//i)
return divisors
def generate_n_primes(n, primes=[], reversed=True):
if primes is None or len(primes) == 0:
p = 2
else:
p = int(primes[-1])
while len(primes) < n:
if p == 2:
p = 3
else:
p += 2
if is_prime(p, primes):
primes.append(p)
if reversed is not None:
return sorted(primes, reverse=reversed)
else:
return primes
def generate_primes_up_to(max_num):
primes = []
cands = [2] + list(range(3, max_num, 2))
while len(cands) > 0:
cand = cands.pop(0)
primes.append(cand)
cands = [c for c in cands if c % cand > 0] # sieve
return primes
def is_prime(n, primes=[2]):
if not primes:
pass
reduced_primes = filter(lambda y: y <= np.sqrt(n), primes)
return all([n%p > 0 for p in reduced_primes])
def read_primes():
f = open('primes')
return (int(i) for i in f.read().split("\n"))
def read_n_primes(n):
return itertools.islice(read_primes(), n)