Rebased projecteuler folder, now includes all contest programming stuff
This commit is contained in:
84
projecteuler/026/main.py
Normal file
84
projecteuler/026/main.py
Normal file
@@ -0,0 +1,84 @@
|
||||
# Find the number d < 1000 for which 1 / d has the longest recurring cycle
|
||||
# in its decimal fraction part
|
||||
|
||||
# It seems like the cycle is never longer than the longest of the cycle length of any of its prime divisors
|
||||
# So say we want to know the length for d and d = a * b, then the cycle for d has the same length as either the cycle for a or b, whichever is longer.
|
||||
|
||||
# So it seems we then only have to check the primes, so first let's get a prime finder in here
|
||||
|
||||
import numpy as np
|
||||
import math
|
||||
|
||||
def maxIndex(ns):
|
||||
result = 0
|
||||
m = ns[0]
|
||||
|
||||
for i in range(len(ns)):
|
||||
if ns[i] > m:
|
||||
result = i
|
||||
m = ns[i]
|
||||
|
||||
return result
|
||||
|
||||
def getPrimes(n):
|
||||
primes = [1 for p in range(n)]
|
||||
primes[0] = 0
|
||||
primes[1] = 0
|
||||
|
||||
x = 2
|
||||
while x < np.sqrt(n):
|
||||
if primes[x] == 1:
|
||||
|
||||
for i in range(x+x, n, x):
|
||||
primes[i] = 0
|
||||
|
||||
x += 1
|
||||
|
||||
result = []
|
||||
for i in range(n):
|
||||
if primes[i]:
|
||||
result.append(i)
|
||||
|
||||
return result
|
||||
|
||||
# Now we need to find out the recurring cycle length for any number
|
||||
# As a benefit for only checking prime number, we know that the cycles will always immediately start after the .'s
|
||||
|
||||
def cycleLength(n):
|
||||
l = int(math.log10(n)) + 1
|
||||
y = 1
|
||||
power = pow(10,l)
|
||||
|
||||
result = 1
|
||||
|
||||
while True:
|
||||
|
||||
x = (y * power) // n
|
||||
rest = y * power - x * n
|
||||
|
||||
if rest == 0:
|
||||
return 0
|
||||
|
||||
elif rest == 1:
|
||||
break
|
||||
|
||||
else:
|
||||
y = rest
|
||||
|
||||
result += 1
|
||||
|
||||
return result * l
|
||||
|
||||
def main():
|
||||
print("Hello, this is Patrick")
|
||||
|
||||
ps = getPrimes(1000)
|
||||
cyclelengths = [cycleLength(p) for p in ps]
|
||||
|
||||
for i in range(len(ps)):
|
||||
print(f"{ps[i]} has length: {cyclelengths[i]}")
|
||||
|
||||
print(f"Biggest cycle is for {ps[maxIndex(cyclelengths)]} with length {max(cyclelengths)}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user