Project Euler 1-7
Project Euler: https://projecteuler.net/
Project Euler | 欧拉计划: https://pe-cn.github.io/
Project Euler 1-7
Project Euler 8-14
Project Euler 15-21 & 67
Project Euler 22-28
Project Euler 29-35
Project Euler 36-42
Project Euler 43-49
Project Euler 50-56
Project Euler 57-63
如果有错误,还望指出,欢迎互相交流学习
随缘更新
Problem 1
Find the sum of the multiples of 3 or 5 below 1000
- sum(the multiples of 3 below 1000) + sum(the multiples of 5 below 1000) - sum(the multiples of 3*5 below 1000)
num_3 = 1000//3
num_5 = 1000//5 - 1
num_3x5 = 1000//(3*5)
Sum_3 = (3+num_3*3)*num_3/2
Sum_5 = (5+num_5*5)*num_5/2
Sum_3x5 = (3*5+num_3x5*3*5)*num_3x5/2
Sum = Sum_3 + Sum_5 - Sum_3x5
print(Sum)
233168.0
Problem 2
Even Fibonacci numbers
-
有个好用的python语法
a, b = b, a+b
Sum = 0
num_0 = 1
num_1 = 2
while num_1 < 4000000:
#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
if num_1%2 == 0:
Sum += num_1
num_0, num_1 = num_1, num_0+num_1
# num_temp = num_1
# num_1 += num_0
# num_0 = num_temp
print(Sum)
4613732
Problem 3: Largest prime factor(质因子)
What is the largest prime factor of the number 600851475143 ?
- 通过NUMBER除以自身的因数,逐步缩小NUMBER的规模
NUMBER = 600851475143
i = 2
res = 1
while NUMBER>2:
if NUMBER%i == 0:
NUMBER = NUMBER//i
res = i
else:
i+=1
print(res)
6857
Problem 4: Largest palindrome(回文数) product
Find the largest palindrome made from the product of two 3-digit numbers.
- 暴力搜索:对900个6位回文数由大到小一次进行因式分解,查找是否存在3位x3位的组合
- python语法:在Python中的while或者for循环之后还可以有else子句,作用是for循环中if条件一直不满足,则最后就执行else语句
# 999 999
# 998 899
# ...
for i in range(999, 100, -1):
num_temp = i%10*100 + (i//10)%10*10 + i//100
num = i * 1000 + num_temp
for i in range(999, 100, -1):
if num%i == 0:
if num//i <= 999 and num//i >= 100:
print(i, num//i, num)
break
else:
continue
break
993 913 906609
Problem 5: Smallest multiple
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
- 遍历1-20,找出每个数的因数且从中去除之前记录下的因数
n = 20
ans = 1
L = []
for i in range(1,n+1):
for j in L:
if i%j == 0:
i = i//j
L.append(i)
print(L)
for i in L:
ans *= i
print(ans)
[1, 2, 3, 2, 5, 1, 7, 2, 3, 1, 11, 1, 13, 1, 1, 2, 17, 1, 19, 1]
232792560
Problem 6: Sum square difference
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
- 平方和公式: ∑ i = 1 n n 2 = n ( n + 1 ) ( 2 n + 1 ) 6 \sum_{i=1}^{n}n^2 = \frac {n(n+1)(2n+1)}{6} i=1∑nn2=6n(n+1)(2n+1)
n = 100
# def sum_of_squares(n):
# if n==1:
# return 1
# else:
# return sum_of_squares(n-1) + n**2
# ans = ((1+n)*n//2)**2 - sum_of_squares(n)
ans = ((1+n)*n//2)**2 - n*(n+1)*(2*n+1)//6
print(ans)
25164150
Problem 7: 10001st prime
What is the 10 001st prime number?
- 因数都是成对出现,如果出现一个大于 x \sqrt {x} x的因数,必然有一个小于 x \sqrt {x} x的因数存在,因此遍历到 x \sqrt {x} x就可以判定一个数是不是质数,缩短判断质数的时间
import time
t = time.clock()
i=0
k=2
n=10001
while i<n-1:
k+=1
# for j in range(2, k):
# if k%j == 0:
# break
for j in range(2,int(k**0.5)+1):
if k%j==0:
break
else:
i+=1
print(k)
# print(time.clock() - t)
104743