Skip to content

Instantly share code, notes, and snippets.

@PEZ
Created January 15, 2009 19:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PEZ/47534 to your computer and use it in GitHub Desktop.
Save PEZ/47534 to your computer and use it in GitHub Desktop.
Python for Project Euler #5
"""Python for Project Euler #5: http://projecteuler.net/index.php?section=problems&id=5
Find the smallest number that is divisible with all integers from 1 to 20"""
#It's the Least Common Multiple; lcm(1,2, ..., 20)
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return (a * b) / gcd(a, b)
llcm = lcm(11, 12)
for n in range(12, 20):
llcm = lcm(n, llcm)
print llcm
#Found the following on the Euler Problem 3 forum, by signature lassevk
#It's quite neat!
i = 1
for k in (range(1, 21)):
if i % k > 0:
for j in range(1, 21):
if (i*j) % k == 0:
i *= j
break
print i
@ahskan
Copy link

ahskan commented Dec 21, 2020

Better Answer:

list = []
for i in range(2,21):
    list.append(i)

for i in range(0, len(list)):
    for j in range(1, i+1):
        if list[i] % list[i-j] == 0:
            list[i] = int(list[i] / list[i-j])

answer = 1

for i in range(0, len(list)):
    answer = answer * list[i]

print(answer)

@Manideepc007
Copy link

for i in range(0, len(list)):
for j in range(1, i+1):
if list[i] % list[i-j] == 0:
list[i] = int(list[i] / list[i-j])

Can you explain this part ?

@joejoe-am
Copy link

from math import prod
from collections import Counter

def get_factors_number(number):
i = 2
factors = []
while number != 1:
if number % i == 0:
number = number / i
factors.append(i)
else:
i += 1
return factors

def can_divided_1_to_n(n):
factors = []
for i in range(1, n):
facts = get_factors_number(i)
c1 = Counter(facts)
c2 = Counter(factors)
diff = c1 - c2
factors += list(diff.elements())
return factors

print(prod(can_divided_1_to_n(20))) # time 0.02 answer 232792560

this will work for all n number you give it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment