Project Euler: Problem 1 (Possible refactorings and run time optimizations)

前端 未结 13 2078
半阙折子戏
半阙折子戏 2020-12-11 08:35

I have been hearing a lot about Project Euler so I thought I solve one of the problems in C#. The problem as stated on the website is as follows:

If w

13条回答
  •  忘掉有多难
    2020-12-11 09:08

    Your approach is brute force apprach, The time complexity of the following approach is O(1), Here we     
    are dividing the given (number-1) by 3, 5 and 15, and store in countNumOf3,countNumOf5, countNumOf15.
    Now we can say that 3 will make AP, within the range of given (number-1) with difference of 3. 
    suppose you are given number is 16, then 
    3=> 3, 6, 9, 12, 15= sum1=>45
    5=> 5, 10, 15  sum2=> 30
    15=> 15 =>   sum3=15  
    Add sum= sum1 and sum2
    
    
    Here 15 is multiple of 3 and 5  so remove sum3 form sum, this will be your answer. **sum=sum-    
    sum3** please check link of my solution on http://ideone.com/beXsam]
    
    import java.util.*;
    class Multiplesof3And5 {        
            public static void main(String [] args){
                Scanner scan=new Scanner(System.in);
                int num=scan.nextInt();
                System.out.println(getSum(num));
            }    
            public static  long getSum(int n){
                int countNumOf3=(n-1)/3;//             
                int countNumOf5=(n-1)/5;           
                int countNumOf15=(n-1)/15;            
                long sum=0;           
                sum=sumOfAP(3,countNumOf3,3)+sumOfAP(5,countNumOf5,5)-sumOfAP(15,countNumOf15,15);
                return sum;
            }
            public static int sumOfAP(int a, int n, int d){
                return (n*(2*a +(n -1)*d))/2;
            }
    }
    

提交回复
热议问题