find the sum of the multiples of 3 and 5 below 1000

前端 未结 12 968
我在风中等你
我在风中等你 2021-01-18 08:04

Ok guys, so I\'m doing the Project Euler challenges and I can\'t believe I\'m stuck on the first challenge. I really can\'t see why I\'m getting the wrong answer despite my

12条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 08:38

    Don't you all think instead of using loops to compute the sum of multiples, we can easily compute sum of n terms using a simple formula of Arithmetic Progression to compute sum of n terms.

    I evaluated results on both using loop and formula. Loops works simply valuable to short data ranges. But when the data ranges grows more than 1010 program takes more than hours to process the result with loops. But the same evaluates the result in milliseconds when using a simple formula of Arithmetic Progression.

    What we really need to do is:
    Algorithm :

    1. Compute the sum of multiples of 3 and add to sum.
    2. Compute the sum of multiples of 5 and add to sum.
    3. Compute the sum of multiples of 3*5 = 15 and subtract from sum.

    Here is code snippet in java from my blog post CodeForWin - Project Euler 1: Multiples of 3 and 5

    n--; //Since we need to compute the sum less than n.
    //Check if n is more than or equal to 3 then compute sum of all divisible by
    //3 and add to sum.  
    if(n>=3) {  
        totalElements = n/3;  
        sum += (totalElements * ( 3 + totalElements*3)) / 2;  
    }  
    
    //Check if n is more than or equal to 5 then compute sum of all elements   
    //divisible by 5 and add to sum.  
    if(n >= 5) {  
        totalElements = n/5;  
        sum += (totalElements * (5 + totalElements * 5)) / 2;  
    }  
    
    //Check if n is more than or equal to 15 then compute sum of all elements  
    //divisible by 15 and subtract from sum.  
    if(n >= 15) {  
        totalElements = n/15;  
        sum -= (totalElements * (15 + totalElements * 15)) / 2;  
    }  
    
    System.out.println(sum); 
    

提交回复
热议问题