Project Euler Problem5

2013-12-12 来源: tianxiaozz 发布在

Smallest multiple

Problem 5

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

From problem 3, we get a list of prime factors of a number . Base on this, we get the prime factors for number from 1 to 20.

And we merge them together. The rule is, we get the largest times for each prime factor. Then we mutiply them.

The python code is as follows:

def getPrimeFactorDic(data):
    dic = {}
    i = 2
    while i <= math.sqrt(data):
    #while i <= data/2:
        if data%i == 0 :
            putIntoDic(dic, i)
            data = (int)(data/i)
            #i = 2
            i += 1
    putIntoDic(dic, data)
    return dic

def putIntoDic(dic, key):
    if key in dic:
        dic[key] += 1
        dic[key] = 1

def mergeIntoDic(dic, key, value):
    if key in dic:
        if value > dic[key]:
            dic[key] = value
        dic[key] = value

myDic = {}
for i in range(1, 21):
    tempDic = getPrimeFactorDic(i)
    for key in tempDic.keys():
        mergeIntoDic(myDic, key, tempDic[key])

mathProduct = 1
for key in myDic.keys():
    mathProduct *= pow(key, myDic[key])