PHP 和 Python實現Project Euler 1、2題

來源:互聯網
上載者:User
最近開始學python,於是就拿Project Euler來練手

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.

運行結果:233168

PHP版本 :

/** * @desc Project Euler 1 * @Author tina * @Date 2015-08-27 */$sum = 0;for($i=0; $i<1000; $i++){    if(($i%3 == 0) || ($i%5 == 0)){        $sum += $i;    }}echo $sum;
python版本:

sum = 0for i in range(1000):    if((i%3 == 0) or (i%5 == 0)):        sum += iprint sum

Problem 2

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

運行結果:4613732

PHP版本:

/** * @desc : Project Euler 2 * @Author : tina  * @Date : 2015-08-27 */$fab1 = 1;$fab2 = 1;$sum = 0;do{    $fab = $fab1+$fab2;    $fab1 = $fab2;    $fab2 = $fab;    if($fab%2 == 0){        $sum += $fab;    }}while($fab < 4000000);echo $sum;

python版本:

fab1 = 1fab2 = 1sum = 0while True :    fab = fab1+fab2    fab1 = fab2    fab2 = fab    if(fab%2 == 0):        sum += fab    if(fab > 4000000) : breakprint sum

其實感覺大體上還是差不多的……但看了一些python介紹,感覺功能很強大,什麼列表、字典、集合資料類型,居然還可以處理複數!!很期待啊!(PS:好像發明Python的這個大牛就是數學出身的,難怪羅!)


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

以上就介紹了PHP 和 Python實現Project Euler 1、2題,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.