|
| 1 | +#coding=utf8 |
| 2 | +''' |
| 3 | +forked from https://blog.dreamshire.com/common-functions-routines-project-euler/ |
| 4 | +''' |
| 5 | +from __future__ import absolute_import |
| 6 | +from math import sqrt, ceil |
| 7 | +from functools import reduce |
| 8 | +import random |
| 9 | +import itertools |
| 10 | + |
| 11 | + |
| 12 | +fact = (1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880) |
| 13 | + |
| 14 | +def factorial(n): return reduce(lambda x,y:x*y,range(1,n+1),1) |
| 15 | + |
| 16 | +def is_perm(a,b): return sorted(str(a))==sorted(str(b)) |
| 17 | + |
| 18 | +def is_palindromic(n): n=str(n); return n==n[::-1] |
| 19 | + |
| 20 | +def is_pandigital(n, s=9): n=str(n); return len(n)==s and not '1234567890'[:s].strip(n) |
| 21 | + |
| 22 | +#--- Calculate the sum of proper divisors for n-------------------------------------------------- |
| 23 | +def d(n): |
| 24 | + s = 1 |
| 25 | + t = sqrt(n) |
| 26 | + for i in range(2, int(t)+1): |
| 27 | + if n % i == 0: s += i + n/i |
| 28 | + if t == int(t): s -= t #correct s if t is a perfect square |
| 29 | + return s |
| 30 | + |
| 31 | +#--- Create a list of all palindromic numbers with k digits-------------------------------------- |
| 32 | +def pal_list(k): |
| 33 | + if k == 1: |
| 34 | + return [1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 35 | + return [sum([n*(10**i) for i,n in enumerate(([x]+list(ys)+[z]+list(ys)[::-1]+[x]) if k%2 |
| 36 | + else ([x]+list(ys)+list(ys)[::-1]+[x]))]) |
| 37 | + for x in range(1,10) |
| 38 | + for ys in itertools.product(range(10), repeat=int(k/2)-1) |
| 39 | + for z in (range(10) if k%2 else (None,))] |
| 40 | + |
| 41 | + |
| 42 | +#--- sum of factorial's digits------------------------------------------------------------------- |
| 43 | +def sof_digits(n): |
| 44 | + if n==0: return 1 |
| 45 | + s = 0 |
| 46 | + while n > 0: |
| 47 | + s, n = s + fact[n % 10], n // 10 |
| 48 | + return s |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | +#--- find the nth Fibonacci number--------------------------------------------------------------- |
| 53 | +def fibonacci(n): |
| 54 | + """ |
| 55 | + Find the nth number in the Fibonacci series. Example: |
| 56 | + |
| 57 | + >>>fibonacci(100) |
| 58 | + 354224848179261915075 |
| 59 | +
|
| 60 | + Algorithm & Python source: Copyright (c) 2013 Nayuki Minase |
| 61 | + Fast doubling Fibonacci algorithm |
| 62 | + http://nayuki.eigenstate.org/page/fast-fibonacci-algorithms |
| 63 | + """ |
| 64 | + if n < 0: |
| 65 | + raise ValueError("Negative arguments not implemented") |
| 66 | + return _fib(n)[0] |
| 67 | + |
| 68 | +# Returns a tuple (F(n), F(n+1)) |
| 69 | +def _fib(n): |
| 70 | + if n == 0: |
| 71 | + return (0, 1) |
| 72 | + else: |
| 73 | + a, b = _fib(n // 2) |
| 74 | + c = a * (2 * b - a) |
| 75 | + d = b * b + a * a |
| 76 | + if n % 2 == 0: |
| 77 | + return (c, d) |
| 78 | + else: |
| 79 | + return (d, c + d) |
| 80 | + |
| 81 | + |
| 82 | +#--- sum of squares of digits------------------------------------------------------------------- |
| 83 | +def sos_digits(n): |
| 84 | + s = 0 |
| 85 | + while n > 0: |
| 86 | + s, n = s + (n % 10)**2, n // 10 |
| 87 | + return s |
| 88 | + |
| 89 | +#--- sum of the digits to a power e------------------------------------------------------------- |
| 90 | +def pow_digits(n, e): |
| 91 | + s = 0 |
| 92 | + while n > 0: |
| 93 | + s, n = s + (n % 10)**e, n // 10 |
| 94 | + return s |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | +#--- check n for prime-------------------------------------------------------------------------- |
| 99 | +def is_prime(n): |
| 100 | + if n <= 1: return False |
| 101 | + if n <= 3: return True |
| 102 | + if n%2==0 or n%3 == 0: return False |
| 103 | + r = int(sqrt(n)) |
| 104 | + f = 5 |
| 105 | + while f <= r: |
| 106 | + if n%f == 0 or n%(f+2) == 0: return False |
| 107 | + f+= 6 |
| 108 | + return True |
| 109 | + |
| 110 | + |
| 111 | + |
| 112 | + |
| 113 | +#--- Miller-Rabin primality test---------------------------------------------------------------- |
| 114 | +def miller_rabin(n): |
| 115 | + """ |
| 116 | + Check n for primalty: Example: |
| 117 | +
|
| 118 | + >miller_rabin(162259276829213363391578010288127) #Mersenne prime #11 |
| 119 | + True |
| 120 | +
|
| 121 | + Algorithm & Python source: |
| 122 | + http://en.literateprograms.org/Miller-Rabin_primality_test_(Python) |
| 123 | + """ |
| 124 | + d = n - 1 |
| 125 | + s = 0 |
| 126 | + while d % 2 == 0: |
| 127 | + d >>= 1 |
| 128 | + s += 1 |
| 129 | + for repeat in range(20): |
| 130 | + a = 0 |
| 131 | + while a == 0: |
| 132 | + a = random.randrange(n) |
| 133 | + if not miller_rabin_pass(a, s, d, n): |
| 134 | + return False |
| 135 | + return True |
| 136 | + |
| 137 | +def miller_rabin_pass(a, s, d, n): |
| 138 | + a_to_power = pow(a, d, n) |
| 139 | + if a_to_power == 1: |
| 140 | + return True |
| 141 | + for i in range(s-1): |
| 142 | + if a_to_power == n - 1: |
| 143 | + return True |
| 144 | + a_to_power = (a_to_power * a_to_power) % n |
| 145 | + return a_to_power == n - 1 |
| 146 | + |
| 147 | + |
| 148 | + |
| 149 | +#--- factor a number into primes and frequency---------------------------------------------------- |
| 150 | +""" |
| 151 | + find the prime factors of n along with their frequencies. Example: |
| 152 | +
|
| 153 | + >>> factor(786456) |
| 154 | + [(2,3), (3,3), (11,1), (331,1)] |
| 155 | + |
| 156 | + Source: Project Euler forums for problem #3 |
| 157 | +""" |
| 158 | +def factor(n): |
| 159 | + f, factors, prime_gaps = 1, [], [2, 4, 2, 4, 6, 2, 6, 4] |
| 160 | + if n < 1: |
| 161 | + return [] |
| 162 | + while True: |
| 163 | + for gap in ([1, 1, 2, 2, 4] if f < 11 else prime_gaps): |
| 164 | + f += gap |
| 165 | + if f * f > n: # If f > sqrt(n) |
| 166 | + if n == 1: |
| 167 | + return factors |
| 168 | + else: |
| 169 | + return factors + [(n, 1)] |
| 170 | + if not n % f: |
| 171 | + e = 1 |
| 172 | + n //= f |
| 173 | + while not n % f: |
| 174 | + n //= f |
| 175 | + e += 1 |
| 176 | + factors.append((f, e)) |
| 177 | + |
| 178 | + |
| 179 | +#--- greatest common divisor---------------------------------------------------------------------- |
| 180 | +def gcd(a, b): |
| 181 | + """ |
| 182 | + Compute the greatest common divisor of a and b. Examples: |
| 183 | + |
| 184 | + >>> gcd(14, 15) #co-prime |
| 185 | + 1 |
| 186 | + >>> gcd(5*5, 3*5) |
| 187 | + 5 |
| 188 | + """ |
| 189 | + if a < 0: a = -a |
| 190 | + if b < 0: b = -b |
| 191 | + if a == 0: return b |
| 192 | + while (b): a, b = b, a%b |
| 193 | + return a |
| 194 | + |
| 195 | + |
| 196 | + |
| 197 | + |
| 198 | +#--- generate permutations----------------------------------------------------------------------- |
| 199 | +def perm(n, s): |
| 200 | + """ |
| 201 | + requires function factorial() |
| 202 | + Find the nth permutation of the string s. Example: |
| 203 | +
|
| 204 | + >>>perm(30, 'abcde') |
| 205 | + bcade |
| 206 | + """ |
| 207 | + if len(s)==1: return s |
| 208 | + q, r = divmod(n, factorial(len(s)-1)) |
| 209 | + return s[q] + perm(r, s[:q] + s[q+1:]) |
| 210 | + |
| 211 | + |
| 212 | + |
| 213 | + |
| 214 | +#--- binomial coefficients----------------------------------------------------------------------- |
| 215 | +def binomial(n, k): |
| 216 | + """ |
| 217 | + Calculate C(n,k), the number of ways can k be chosen from n. Example: |
| 218 | + |
| 219 | + >>>binomial(30,12) |
| 220 | + 86493225 |
| 221 | + """ |
| 222 | + nt = 1 |
| 223 | + for t in range(min(k, n-k)): |
| 224 | + nt = nt * (n-t) // (t+1) |
| 225 | + return nt |
| 226 | + |
| 227 | + |
| 228 | +#--- catalan number------------------------------------------------------------------------------ |
| 229 | +def catalan_number(n): |
| 230 | + """ |
| 231 | + Calculate the nth Catalan number. Example: |
| 232 | + |
| 233 | + >>>catalan_number(10) |
| 234 | + 16796 |
| 235 | + """ |
| 236 | + nm = dm = 1 |
| 237 | + for k in range(2, n+1): |
| 238 | + nm, dm = (nm*(n+k), dm*k) |
| 239 | + return nm / dm |
| 240 | + |
| 241 | + |
| 242 | + |
| 243 | +#--- generate prime numbers---------------------------------------------------------------------- |
| 244 | +def prime_sieve(n): |
| 245 | + """ |
| 246 | + Return a list of prime numbers from 2 to a prime < n. Very fast (n<10,000,000) in 0.4 sec. |
| 247 | + |
| 248 | + Example: |
| 249 | + >>>prime_sieve(25) |
| 250 | + [2, 3, 5, 7, 11, 13, 17, 19, 23] |
| 251 | +
|
| 252 | + Algorithm & Python source: Robert William Hanks |
| 253 | + http://stackoverflow.com/questions/17773352/python-sieve-prime-numbers |
| 254 | + """ |
| 255 | + sieve = [True] * int(n/2) |
| 256 | + for i in range(3,int(n**0.5)+1,2): |
| 257 | + if sieve[int(i/2)]: |
| 258 | + sieve[i*int(i/2)::i] = [False] * (int((n-i*i-1)/(2*i))+1) |
| 259 | + return [2] + [2*i+1 for i in range(1,int(n/2)) if sieve[i]] |
| 260 | + |
| 261 | + |
| 262 | +#--- bezout coefficients-------------------------------------------------------------------------- |
| 263 | +def exgcd(a,b): |
| 264 | + """ |
| 265 | + Bézout coefficients (u,v) of (a,b) as: |
| 266 | +
|
| 267 | + a*u + b*v = gcd(a,b) |
| 268 | +
|
| 269 | + Result is the tuple: (u, v, gcd(a,b)). Examples: |
| 270 | +
|
| 271 | + >>> bezout(7*3, 15*3) |
| 272 | + (-2, 1, 3) |
| 273 | + >>> bezout(24157817, 39088169) #sequential Fibonacci numbers |
| 274 | + (-14930352, 9227465, 1) |
| 275 | +
|
| 276 | + Algorithm source: Pierre L. Douillet |
| 277 | + http://www.douillet.info/~douillet/working_papers/bezout/node2.html |
| 278 | + """ |
| 279 | + u, v, s, t = 1, 0, 0, 1 |
| 280 | + while b !=0: |
| 281 | + q, r = divmod(a,b) |
| 282 | + a, b = b, r |
| 283 | + u, s = s, u - q*s |
| 284 | + v, t = t, v - q*t |
| 285 | + |
| 286 | + return (u, v, a) |
| 287 | + |
| 288 | + |
| 289 | + |
| 290 | +def mod_inverse(a,b): |
| 291 | + x,y,z = exgcd(a,b) |
| 292 | + return x; |
| 293 | + |
| 294 | +def phi(x): |
| 295 | + if x==1: |
| 296 | + return 1; |
| 297 | + factors = factor(x); |
| 298 | + ans = x; |
| 299 | + for prime in factors: |
| 300 | + ans=int(ans / prime[0]*(prime[0]-1)) |
| 301 | + return ans |
| 302 | + |
| 303 | +def miu(x): |
| 304 | + if x==1: |
| 305 | + return 1; |
| 306 | + factors = factor(x) |
| 307 | + for prime in factors: |
| 308 | + if prime[1]>1: |
| 309 | + return 0; |
| 310 | + return 1-(len(factors) and 1)*2 |
| 311 | + |
| 312 | + |
| 313 | +#--- number base conversion ------------------------------------------------------------------- |
| 314 | +#source: http://interactivepython.org/runestone/static/pythonds/Recursion/pythondsConvertinganIntegertoaStringinAnyBase.html |
| 315 | +def dec2base(n,base): |
| 316 | + convertString = "0123456789ABCDEF" |
| 317 | + if n < base: |
| 318 | + return convertString[n] |
| 319 | + else: |
| 320 | + return dec2base(n//base,base) + convertString[n%base] |
| 321 | + |
| 322 | +#--- number to words ---------------------------------------------------------------------------- |
| 323 | +#this function copied from stackoverflow user: Developer, Oct 5 '13 at 3:45 |
| 324 | +def n2words(num,join=True): |
| 325 | + '''words = {} convert an integer number into words''' |
| 326 | + units = ['','One','Two','Three','Four','Five','Six','Seven','Eight','Nine'] |
| 327 | + teens = ['','Eleven','Twelve','Thirteen','Fourteen','Fifteen','Sixteen', \ |
| 328 | + 'Seventeen','Eighteen','Nineteen'] |
| 329 | + tens = ['','Ten','Twenty','Thirty','Forty','Fifty','Sixty','Seventy', \ |
| 330 | + 'Eighty','Ninety'] |
| 331 | + thousands = ['','Thousand','Million','Billion','Trillion','Quadrillion', \ |
| 332 | + 'Quintillion','Sextillion','Septillion','Octillion', \ |
| 333 | + 'Nonillion','Decillion','Undecillion','Duodecillion', \ |
| 334 | + 'Tredecillion','Quattuordecillion','Sexdecillion', \ |
| 335 | + 'Septendecillion','Octodecillion','Novemdecillion', \ |
| 336 | + 'Vigintillion'] |
| 337 | + words = [] |
| 338 | + if num==0: words.append('zero') |
| 339 | + else: |
| 340 | + numStr = '%d'%num |
| 341 | + numStrLen = len(numStr) |
| 342 | + groups = int((numStrLen+2)/3) |
| 343 | + numStr = numStr.zfill(groups*3) |
| 344 | + for i in range(0,groups*3,3): |
| 345 | + h,t,u = int(numStr[i]),int(numStr[i+1]),int(numStr[i+2]) |
| 346 | + g = groups-(int(i/3)+1) |
| 347 | + if h>=1: |
| 348 | + words.append(units[h]) |
| 349 | + words.append('Hundred') |
| 350 | + if t>1: |
| 351 | + words.append(tens[t]) |
| 352 | + if u>=1: words.append(units[u]) |
| 353 | + elif t==1: |
| 354 | + if u>=1: words.append(teens[u]) |
| 355 | + else: words.append(tens[t]) |
| 356 | + else: |
| 357 | + if u>=1: words.append(units[u]) |
| 358 | + if (g>=1) and ((h+t+u)>0): words.append(thousands[g]+'') |
| 359 | + if join: return ' '.join(words) |
| 360 | + return words |
0 commit comments