python解決project euler題目的樂趣

 寒假期間學習了python,如今基本上就能上手使用它來解決project euler裏面的題目了,用python真的是沒得說的,一個字「贊」。在C++中須要用一大堆代碼實現的算法,在python中,只須要那麼短短几行。並且還有驚豔的運行速度。借用《可愛的python》裏面的一句話:「人生苦短,我用python」。python

 

【project euler 055】git

求通過一系列規則不能獲得迴文數的數的個數。題目在此:web

If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.算法

Not all numbers produce palindromes so quickly. For example,express

349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337編程

That is, 349 took three iterations to arrive at a palindrome.less

Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).ide

Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.函數式編程

How many Lychrel numbers are there below ten-thousand?函數

NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.

 

思路:從1到10000進行逐個掃描,對於每一個數進行判斷,是否通過上述規則都不能產生迴文數。在python中,有很方便的作法判斷一個數是不是迴文數。只需比較對稱的列表位置是否相同 arr[i] == arr[lenth-1-i], i從0開始。固然作完以後發現有牛人用幾行代碼就把一切搞定了。不信請看:

 

def Lycheck(n):
   for i in range(0,50):
       n = n+int(str(n)[::-1])
       if str(n)==str(n)[::-1]: return False
   return True
len([n for n in range(10000) if Lycheck(n)])

 

python給個人一個印象就是列表操做很方便,類型轉換超級自由,並且對於大數的運算很是快。這道題目用python解只用了1s。amazing! 另一個很特別的是,python支持函數式編程,lambda算子能夠建立函數對象,傳入某個程式裏面,很是了得。本人在DES的程序中,也看到了相似lambda(x,y: x^y)的函數,很是地神奇,可以對map裏面的元素都執行這個操做。

 

【project euler 056】

A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.

Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?

思路: 很明顯,這個位的和要大,顯然要夠長。既要夠長,每位數字的數字也要夠長。我腦海裏面立馬蹦出了99的99次方這樣的數字。可是不能想固然,我仍是從91開始,計算到100,鐵定可以找到那個各位和最大的數。程序以下:

# project euler 56
# !/usr/bin/python
# -*- coding: utf-8 -*-
import sys


def power_digit_sum():
	max_digits_sum = 0
	for i in range(91,100):
		for j in range(91,100):
			power_num = pow(i,j)
			print power_num
			digits_sum = sum_digits(power_num)
			print digits_sum
			if digits_sum > max_digits_sum:
				max_digits_sum = digits_sum
	print max_digits_sum
			
			
def sum_digits( power_num):
	digits_sum = 0
	while power_num != 0 :
		rear_num = power_num % 10
		power_num = power_num / 10
		digits_sum += rear_num
	return digits_sum
	#return sum(map(int, power_num))


power_digit_sum()

 

運行就可以找到答案了。

【project euler 057】

 

It is possible to show that the square root of two can be expressed as an infinite continued fraction.

√ 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

By expanding this for the first four iterations, we get:

1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...

The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.

In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?

思路:找規律,發現只要用幾個變量就能夠徹底表示好這個式子的模式,從下往上看,有至關一部分x=(1/(2+1/2)),是由上一步產生的,而每步都是1+1/(2+x)組成的,而x的產生能夠是遞歸的。另外第一次i=0的時候,比較特殊,是1+x的模式。

總結規律以下:

 

 

# 計算展開式 e
# count 第幾回展開, 採用遞歸法則
def cal_expansion(count,a,b):
   c = 1   
   d = 1    
   e = 2   # (2 + 1/2) 加號前的2
   if count == 0:  # first time is special
     c = b + a
     d = b
     return a,b,c,d   # 遞歸最底層
   elif count > 0:  # the second time is special
     a = (b*e) + a
     a,b = swap(a,b)
     #print count,a,b
     count = 0            ​# 由於採用了自上而下,故而不這裏的遞歸須要有所修改,直接奔第0次
     return  cal_expansion(count,a,b) #遞歸調用
 
# swap function
def swap(a, b):
    b,a = a,b
    return a,b


TIMES = 1000
# every time 
a,b,c,d = 1,2,1,1
count = 0
strc,strd ="",""
for i in range(0,TIMES):
    print i,"(",a,"/",b,")",c,d
    a,b,c,d = cal_expansion(i,a,b)   # 重複傳遞的a/b部分,如1/2, 2/5,5/12等,以及整個式子的結果c/d,如3/2
    strc,strd = str(c),str(b)
    if len(strc) > len(strd):  #位數比較
        count +=1
print count

 

程序採用了遞歸,可是考慮到從上往下計算將會節省不少時間,故而用迭代進行計算。原覺得迭代和遞歸是矛盾的,不能同時使用的,可是我先計算出的成果,從是可以運用到下一步的計算當中。這令我很是有成就感。下面是運行的例子:

點擊查看原圖

連接 projectEuler

相關文章
相關標籤/搜索