-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUseful.py
127 lines (87 loc) · 1.73 KB
/
Useful.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
from math import sqrt, floor
def factor(n):
lim = floor(sqrt(float(n)))
ind = 2
while ind <= lim:
if n % ind == 0:
return([ind] + factor(n // ind))
ind += 1
return [n]
def toDigits(n):
if n < 10:
return([n])
return(toDigits(n // 10) + [n % 10])
def nPrimes(n):
primes = [2]
cur = 3
while len(primes) < n:
top = floor(sqrt(cur))
for p in primes:
if p > top:
primes.append(cur)
break
elif cur % p == 0:
break
cur += 1
return(primes)
def primesUnder(n):
primes = [2]
cur = 3
while cur < n:
top = floor(sqrt(cur))
for p in primes:
if p > top:
primes.append(cur)
break
elif cur % p == 0:
break
cur += 1
return(primes)
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
def isSquare(n):
rt = isqrt(n)
return(rt**2 == n)
def numDivisors(n):
lim = floor(sqrt(float(n)))
ind = 2
expProd = 1
while ind <= lim:
expCount = 1
while n % ind == 0:
expCount += 1
n //= ind
expProd *= expCount
ind += 1
if expCount > 1:
lim = floor(sqrt(float(n)))
if n == 1:
return(expProd)
else:
return(2 * expProd)
def divisors(n):
lim = floor(sqrt(float(n)))
ind = 2
divs = [1]
while ind <= lim:
if n % ind == 0:
if ind * ind == n:
divs += [ind]
else:
divs += [ind, n // ind]
ind += 1
divs.sort()
return divs
def isPrime(n):
if n < 2:
return False
lim = floor(sqrt(float(n)))
for i in range(2, lim + 1):
if n % i == 0:
return False
return True