Thread: Project Euler Problem 2 Solution

  1. #1
    Registered User
    Join Date
    Jun 2013
    Posts
    20

    Project Euler Problem 2 Solution

    Hi, I have just started working on Project Euler and I have completed problem 2 .I was just wondering if there is a better implementation that is better than one I have implemented and what could be ideal or most efficient solution for this problem.

    Here is my code implementation for this.
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    main(){
    	int i;
    	int j=0;
    	int numberOfItems=100;
    	long sum[numberOfItems];
    	int sumOfEvenNumbers;
    	for(i=0;i<numberOfItems;i++){
    		
    		if(i==0|| i==1){
    			
    			if(i==0){
    				sum[0]=1;
    				
    			}else{
    				
    				sum[1]=sum[0]+1;
    				
    				
    			}
    					
    		}else{
    			
    			sum[i]=sum[i-1]+sum[i-2];
    			
    			
    		}
    		
    		if(sum[i]%2==0){
    				
    				if(sum[i]>4000000){
    					
    					break;
    					
    				}		
    				if(j==0){
    						
    					sumOfEvenNumbers=sum[i];
    						
    				}else{
    						
    						sumOfEvenNumbers=sumOfEvenNumbers+sum[i];
    						
    				}
    				printf("%d\n",sum[i]);
    				j++;
    				
    				
    		}
    		
    		
    	}
    	
    	printf("\nThe sum of even numbers is %d\n",sumOfEvenNumbers);
    	
    	
    	return EXIT_SUCCESS;	
    }

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You could do it like this:
    Code:
    #include <stdio.h>
    
    #define MAX_FIB 4000000
    
    int main(void) {
    	int a = 1, b = 1, c = 1, sum = 0;
    
    	while (c <= MAX_FIB) {
    		if (c % 2 == 0)
    			sum += c;
    		c = a + b;
    		a = b;
    		b = c;
    	}
    
    	printf("\nSum: %d\n", sum);
    
    	return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Project Euler 22
    By deadrabbit in forum C Programming
    Replies: 1
    Last Post: 06-23-2012, 11:22 PM
  2. Project Euler problem
    By nimitzhunter in forum C++ Programming
    Replies: 6
    Last Post: 04-15-2012, 09:00 PM
  3. Project Euler Problem 8
    By deadrabbit in forum C Programming
    Replies: 2
    Last Post: 10-06-2011, 10:56 PM
  4. Project Euler Problem 14 Segfault
    By vincent01910 in forum C Programming
    Replies: 5
    Last Post: 11-04-2009, 05:56 AM
  5. Project Euler problem 3
    By SELFMADE in forum C Programming
    Replies: 7
    Last Post: 09-16-2009, 03:33 AM

Tags for this Thread