Last active
August 29, 2015 14:10
-
-
Save ebartrum/4b241501c88d0c17d48d to your computer and use it in GitHub Desktop.
A solution to the 5th Euler Challenge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""I wish to create a function lcm(x) which gives the lowest common multiple of an array of numbers x""" | |
# I will need the factor function | |
def factor(x): | |
array=[] | |
i=1 | |
while (i<=x): | |
if x%i==0: | |
array.append(i) | |
i+=1 | |
return array | |
# And the prime function | |
def prime(x): | |
if factor(x)==[1,x]: | |
return True | |
else: | |
return False | |
# now combine these to give a prime factor function | |
def primeFactor(x): | |
ans=[] | |
y=factor(x) | |
for z in y: | |
if prime(z): | |
ans.append(z) | |
return ans | |
#A function output how many times x divides y: | |
def powerDivide(x,y): | |
ans=0 | |
n=0 | |
while y%(pow(x,n))==0: | |
n+=1 | |
return n-1 | |
#Now define a function that outputs the highest power of 2 that divides any element of an array x: | |
def powerTwo(x): | |
ans=0 | |
for y in x: | |
if powerDivide(2,y)>ans: | |
ans=powerDivide(2,y) | |
return ans | |
#Now generalise the above to any prime p: | |
def power(p,x): | |
ans=0 | |
for y in x: | |
if powerDivide(p,y)>ans: | |
ans=powerDivide(p,y) | |
return ans | |
#Define a function that gives the primes dividing the elements of x: | |
def primes(x): | |
ans=[] | |
for y in x: | |
ans+=primeFactor(y) | |
ans=list(set(ans)) | |
return ans | |
#Define a function copy(x,n) giving an array containing n copies of x: | |
def copy(x,n): | |
ans=[] | |
m=0 | |
while m<n: | |
ans.append(x) | |
m+=1 | |
return ans | |
#Define a function that computes the prime decomposition as an array of lcm(x): | |
def primeDecompLcm(x): | |
ans=[] | |
for y in primes(x): | |
ans+=copy(y,power(y,x)) | |
return ans | |
#Define a function that multiplies the elements of an array: | |
def mult(x): | |
ans=1 | |
for y in x: | |
ans*=y | |
return ans | |
#define the lcm function | |
def lcm(x): | |
return mult(primeDecompLcm(x)) | |
print(lcm(range(1,20))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment