Saturday, January 25, 2014

Project Euler Problem 1

Hi Friends,

I started solving Project Euler problems recently and found them to be really interesting. So I though of discussing my approach and solutions with the world. I will code my answers in C. So here we start.

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.

The problem is pretty easy and straight forward. Just check all the numbers from 3 to 999 if they are divisible by 3 or 5 and add them if they are.
Here is my code:
1:  #include <stdio.h>  
2:  int main(void)  
3:  {  
4:       int sum=0,i;  
5:       for(i=3;i<1000;i++){  
6:            if(i%3==0 || i%5==0)  
7:                 sum+=i;  
8:       }  
9:       printf("%d",sum);  
10:       return 0;       
11:  }  
Do comment if you have any alternate solution.

2 comments:

  1. int main ()
    {
    int sum=0,sum1=0,sum2=0,i;
    for(i=3;i<1000;i=i+3)
    {
    sum1+=i;

    }

    for (i=5;i<1000;i=i+5)
    {
    sum+=i;


    }

    for(i=15;i<1000;i=i+15)
    {
    sum2+=i;
    }

    sum=sum+sum1-sum2;
    printf("%d",sum);
    return 0;
    }

    ReplyDelete
  2. Sir if n is no of iterations your code will have more complexity O(997)while mine code O(333)..Please correct me if in case i made any mistake
    Thanks

    ReplyDelete