Thursday, January 1, 2015

Project Euler problem 2 Solution in C and python

Q: 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.

Solution in C:

#include <stdio.h>

int main(){
long long int a=1, b=2, sum=1, esum=2//we add 2 already bcoz we know 2 is a even term of fabanacii series;

while (sum<4000000){
printf("%d \t",sum);
sum=a+b;//sum holds the next number in the series
a=b;
b=sum;
if (sum%2==0){
esum+=b;//adding all the even terms of the series
}


}

printf("\n \nsum of even terms is %d", esum);
getchar();

}


Solution in python(3):

a=1
b=2
no=1
evensum=2
while (no<4000000):
    no=a+b
    a=b
    b=no
    if no%2==0:
        evensum=evensum+no

print(evensum)


Saturday, December 20, 2014

Project Euler problem 1 Solution in C, python and using pen and paper

Q:-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.

Solution using C:

#include<stdio.h>

int main(){
int a,sum=0;

//going through all numbers from 1-1000
for (a=1;a<1000;a++){
if (a%3==0 || a%5==0){//check whether each number is divisible by 3 or 5
sum +=a;} //if so add that number to sum
}

printf("sum is : %d", sum);
getchar();

}


Solution using Python(3):

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


Solution using pen and paper:

using the formula  Sn=n*(a+l)/2 use for both numbers divisible by 3 and 5 seperatly and add the sum.