Home >Backend Development >PHP Tutorial >PHP and Python implement Project Euler questions 1 and 2

PHP and Python implement Project Euler questions 1 and 2

WBOY
WBOYOriginal
2016-07-30 13:30:211058browse

I started learning python recently, so I used Project Euler to practice

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.

Run result: 233168

PHP version:

/**
 * @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 version:

sum = 0
for i in range(1000):
    if((i%3 == 0) or (i%5 == 0)):
        sum += i
print 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.

Run result: 4613732

PHP version:

/**
 * @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 version:

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

In fact, it feels generally the same... But after reading some python introductions, I feel that the functions are very powerful. Lists, dictionaries, and set data types can actually handle complex numbers! ! Looking forward to it! (PS: It seems that the great man who invented Python was born in mathematics, no wonder Luo!)

Copyright Statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.

The above introduces the implementation of Project Euler questions 1 and 2 in PHP and Python, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn