首页 » Algorithm, Project Eular, Python » Project Eular #4 #5 #6 (Python)
01

接着扫四道水题
#4 Find the largest palindrome made from the product of two 3-digit numbers.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

#!/usr/bin/env python

biggest = 0

def isPalindromic(num):
    num_str = str(num)
    num_halflen = len(num_str)/2
    for idx in range(0, num_halflen):
        if num_str[idx] != num_str[-(idx+1)]:
            return False
    return True

for x in range(100, 999):
    for y in range(100, 999):
        if isPalindromic(x*y) and x*y > biggest:
            biggest = x*y

print biggest

#5 What is the smallest number divisible by each of the numbers 1 to 20?

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 number that is evenly divisible by all of the numbers from 1 to 20?

#!/usr/bin/env python

def isPrimeUnder20(num):
    for tmp in range(2, num):
        if num%tmp == 0:
            return False
    return True

factor_list = []

for x in range(2, 20):
    if isPrimeUnder20(x):
        power_x = 1
        while x**power_x <= 20:
            power_x += 1
        factor_list.append(x**(power_x-1))
        print x,power_x-1

prod = 1
for x in factor_list:
    prod *= x

print prod

#6 What is the difference between the sum of the squares and the square of the sums?

The sum of the squares of the first ten natural numbers is,
1^(2) + 2^(2) + ... + 10^(2) = 385

The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^(2) = 55^(2) = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

#!/usr/bin/env python

sum_of_square = 0
for x in range(1, 101):
    sum_of_square += x**2

sum_tmp = 0
for x in range(1, 101):
    sum_tmp += x
square_of_sum = sum_tmp**2

delta = square_of_sum - sum_of_square
print delta

, ,

发表评论