Project Euler Problem1

Multiples of 3 and 5

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

the direct way  the answer :

def isMutiple(target, divider1, divider2):
    if (target % divider1 == 0) or (target % divider2 == 0):
        return True
    return False

a = 3
b = 5
total = 0
for i in range(1, 1000):
    if isMutiple(i, a, b):
        total += i
print("Total result is : ", total)

The solution above needs to iterate everyone from 1 to 1000, Considering that 1 times, 2 times ,3 times of one numbers, we can rewrite it .

Here is folllows:

def getCount(start, end, divider):
    startDividend = 0
    endDividend = 0
    if start%divider == 0:
        startDividend = start
    else:
        startDividend = (int)(start/divider + 1)*divider 
    if end%divider == 0:
        endDividend = end
    else:
        endDividend = (int)(end/divider)*divider
    count = int((startDividend + endDividend)/2*((endDividend-startDividend)/divider + 1))
  
    return count

a = 0
b = 999
total = 0
total += getCount(a, b, 3)
total += getCount(a, b, 5)
total -= getCount(a, b, 15)  #minus the common mutiples of 3 and 5
        
print("Total result is : ", total)

 

posted @ 2013-12-10 16:38  tianxiaozz  阅读(158)  评论(0)    收藏  举报