简体   繁体   English

Java N的3或5的倍数之和

[英]Java Sum of multiples of 3 or 5 below N

Find the sum(integer) of all the multiples of 3 or 5 below N. I have used the normal AP series formula for this calculation...but two of the test cases are coming wrong.Anyone can tell me whats wrong with this code? 找出N 以下 3或5的所有倍数的总和(整数)。我使用正常的AP系列公式进行此计算...但是有两个测试用例出了错,任何人都可以告诉我这段代码有什么问题? I have not used loop that that shows termination due to timeout 我没有使用过显示由于超时而终止的循环

   int T = sc.nextInt();
   double f1 =0;
   double f2 =0;
   double f3 =0;
   double sum =0;
   for(int i =0; i<T; i++){
       int n = sc.nextInt();

  // n1,n2,n3 are the number of multiples 
   int n1 = (n-1)/3;   
   int n2 = (n-1)/5;   
   int n3 = (n-1)/15;

 // summation formula of AP series  
   f1 = (n1/2.0)*(6+(n1-1)*3);   
   f2 = (n2/2.0)*(10+(n2-1)*5);
   f3 = (n3/2.0)*(30+(n3-1)*15);

// summation multiples of 3 OR 5    
   sum = f1-f3+f2;

// Printing the final integer
   System.out.println((int)sum);
   }
}

} }

private int Sum(int N) {
    int sum = 0;
    for (int i = 3; i < N; i++) {
        if (i % 3 == 0 || i % 5 == 0) {
            sum += i;
        }
    }
    return sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM