Project Euler

最近发现了一个很有趣的网站,Project Euler

上面全是数学题,不过大多需要用编程解决

Problem 3:

求:600851475143的最大素因子。

解:编了个程序,迅速水过,看官方的题解,加了一些优化。其实可以打个素数表继续优化。

 

 

Problem 4:

求:由两个三位数相乘得到的最大的回文数(P = a*b)。

解:枚举100~999,判断成绩是否是回文数,求出最大的一个。

改进一:可假设a<=b,且循环从999开始递减进行。

改进二:由111111 = 143*777,可知P为六位数,设:

P = 100000x + 10000y + 1000z + 100z + 10y + x

P = 100001x + 10010y + 1100z

p = 11(9091x + 910y + 100z)

则a,b中至少有一个是11的倍数,由此可在进一步限制迭代条件,进行加速。

 

代码
1 Problem 4:
2 function reverse(n)
3 reversed = 0
4 while n > 0
5 reversed = 10*reversed + n mod 10
6 n = n/10
7 return reversed
8
9 function isPalindrome(n)
10 return n = reverse(n)
11
12 largestPalindrome = 0;
13 a = 999
14  while a >= 100
15 if a mod 11 = 0
16 b = 999
17 db = 1
18 else
19 b = 999 //The largest number less than or equal 999
20   db = 11 // and divisible by 11
21  
22 while b >= a
23 if a*b <= largestPalindrome
24 break
25 if isPalindrome(a*b)
26 largestPalindrome = a*b
27 b = b-db
28 a = a-1
29
30 output largestPalindrome

 

Problem 6:

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

  前100个自然数的和的平方与平方的和的差。

解:两个公式。

 

Problem 7:

求:第10001个素数

解:1.素数筛选法。

2. 改进的素数判定法,根据:

[1].所有的素数除了2都是奇数,

[2].所有比3大的素数都可以写成6k+1 或6k-1的形式,

[3].任何一个数n至多有一个比大的素因子。

 

p7
//经验证:f=5, {f,f+2|f+=6} 可以涵盖所有的素数
Function isPrime(n)
if n=1 then return false
else
if n<4 then return true
else
if n mod 2=0 then return false
else
if n<9 then return true
else
if n mod 3=0 then return false
else
r
=floor(sqrt(n))
f
=5
while f<=r
if n mod f=0 then return false
if n mod (f+2)=0 then return false
f
=f+6
endwhile
return true
End Function

 

 

posted @ 2010-08-31 21:46  superbin  阅读(632)  评论(0编辑  收藏  举报