Java 求1000以下的3和5的倍数之和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19691830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:26:07  来源:igfitidea点击:

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

java

提问by Tloz

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 code looking functional:

好的,所以我正在做 Project Euler 挑战,我不敢相信我被困在第一个挑战上。尽管我的代码看起来很实用,但我真的不明白为什么我得到了错误的答案:

import java.util.ArrayList;


public class Multithree {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        ArrayList<Integer> x = new ArrayList<Integer>();
        ArrayList<Integer> y = new ArrayList<Integer>();
        int totalforthree = 0;
        int totalforfive = 0;

        int total =0;

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 3 == 0){
                x.add(temp);
                totalforthree += temp;
            }
        }

        for(int temp =0; temp < 1000 ; temp++){
            if(temp % 5 == 0){
                y.add(temp);
                totalforfive += temp;
            }
        }

        total = totalforfive + totalforthree;



        System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);

    }

}

I'm getting the answer as 266333 and it says it's wrong...

我得到的答案是 266333,它说这是错误的...

采纳答案by Todoy

you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...

您应该对两者使用相同的 for 循环以避免重复计算两者的倍数。比如 15,30...

   for(int temp =0; temp < 1000 ; temp++){
        if(temp % 3 == 0){
            x.add(temp);
            totalforthree += temp;
        }else if(temp % 5 == 0){
            y.add(temp);
            totalforfive += temp;
        }
    }

回答by Arash Saidi

You are counting some numbers twice. What you have to do is add inside one for loop, and use an if-else statement where if you find multiples of 3, you do not count them in 5 as well.

您正在计算一些数字两次。您需要做的是在一个 for 循环中添加,并使用 if-else 语句,如果您找到 3 的倍数,则也不会将它们计入 5。

 if(temp % 3 == 0){
     x.add(temp);
     totalforthree += temp;
 } else if(temp % 5 == 0){
     y.add(temp);
     totalforfive += temp;
 }

回答by Sunil MG

Logics given above are showing wrong answer, because multiples of 3 & 5 are taken for calculation. There is something being missed in above logic, i.e., 15, 30, 45, 60... are the multiple of 3 and also multiple of 5. then we need to ignore such while adding.

上面给出的逻辑显示错误答案,因为计算时采用 3 和 5 的倍数。在上面的逻辑中遗漏了一些东西,即 15、30、45、60……是 3 的倍数,也是 5 的倍数。那么我们在添加时需要忽略这些。

    public static void main(String[] args) {
    int Sum=0, i=0, j=0;
    for(i=0;i<=1000;i++)
        if (i%3==0 && i<=999)
            Sum=Sum+i;
    for(j=0;j<=1000;j++)
        if (j%5==0 && j<1000 && j*5%3!=0)
            Sum=Sum+j;
    System.out.println("The Sum is "+Sum);
}

回答by Ojonugwa Jude Ochalifu

Okay, so this isn't the best looking code, but it get's the job done.

好的,所以这不是最好看的代码,但它完成了工作。

public class Multiples {

public static void main(String[]args) {
    int firstNumber = 3;
    int secondNumber = 5;
    ArrayList<Integer> numberToCheck = new ArrayList<Integer>();
    ArrayList<Integer> multiples = new ArrayList<Integer>();
    int sumOfMultiples = 0;
    for (int i = 0; i < 1000; i++) {
       numberToCheck.add(i);

       if (numberToCheck.get(i) % firstNumber == 0 || numberToCheck.get(i) % secondNumber == 0) {
           multiples.add(numberToCheck.get(i));
       }

    }

    for (int i=0; i<multiples.size(); i++) {

     sumOfMultiples += multiples.get(i);

    }
    System.out.println(multiples);
    System.out.println("Sum Of Multiples: " + sumOfMultiples);

}

}

回答by Parag Satav

If number is 10 then multiple of 3 is 3,6,9 and multiple of 5 is 5,10 total sum is 33 and program gives same answer:

如果数字是 10,那么 3 的倍数是 3,6,9,5 的倍数是 5,10 总和是 33,程序给出相同的答案:

package com.parag;

/*
 * @author Parag Satav
 */
public class MultipleAddition {

    /**
     * @param args
     */
    public static void main( final String[] args ) {
    // TODO Auto-generated method stub

    ArrayList<Integer> x = new ArrayList<Integer>();
    ArrayList<Integer> y = new ArrayList<Integer>();
    int totalforthree = 0;
    int totalforfive = 0;
    int number = 8;

    int total = 0;

    for ( int temp = 1; temp <= number; temp++ ) {
        if ( temp % 3 == 0 ) {
            x.add( temp );
            totalforthree += temp;
        }

        else if ( temp % 5 == 0 ) {
            y.add( temp );
            totalforfive += temp;
        }
    }

    total = totalforfive + totalforthree;
    System.out.println( "multiples of 3 : " + x );
    System.out.println( "multiples of 5 : " + y );
    System.out.println( "The multiples of 3 or 5 up to " + number + " are: " + total );

}

}

回答by Pankaj Prakash

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.

难道你们都认为不是使用循环来计算倍数的总和,我们可以使用简单的算术级数公式轻松计算 n 项的总和来计算 n 项的总和

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 1010program 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.

我使用循环和公式评估了结果。循环对短数据范围非常有用。但是当数据范围增长超过 10 10程序需要几个小时来处理循环的结果。但是当使用简单的算术级数公式时,同样以毫秒为单位评估结果。

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.
  1. 计算 3 的倍数之和并添加到 sum。
  2. 计算 5 的倍数之和并添加到总和。
  3. 计算 3*5 = 15 的倍数之和并从总和中减去。

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

这是我的博客文章CodeForWin - Project Euler 1: Multiples of 3 and 5中的 Java 代码片段

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); 

回答by Surya Singh

public class Solution {
    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        while (t>0){
            int sum = 0;
            int count =0;
            int n = sc.nextInt();
            n--; 
            System.out.println((n/3*(6+(n/3-1)*3))/2 + (n/5*(10+(n/5-1)*5))/2 - (n/15*(30+(n/15-1)*15))/2);
            t--;
    }
}
}

回答by Ritesh

How I solved this is that I took an integer value (initialized to zero) and kept on adding the incremented value of i, if its modulo with 3 or 5 gives me zero.

我如何解决这个问题是我取了一个整数值(初始化为零)并继续添加 i 的增量值,如果它的模数 3 或 5 给我零。

private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
        sum += i;
    }
}
return sum;
}

回答by Perry Thomson

I did this several ways and several times. The fastest, cleanest and simplest way to complete the required code for Java is this:

我这样做了好几次。完成 Java 所需代码的最快、最干净和最简单的方法是:

public class MultiplesOf3And5 {

public static void main(String[] args){

System.out.println("The sum of the multiples of 3 and 5 is: " + getSum());

}

private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
        sum += i;
    }
}
return sum;
}

If anyone has a suggestion to get it down to fewer lines of code, please let me know your solution. I'm new to programming.

如果有人建议减少代码行数,请告诉我您的解决方案。我是编程新手。

回答by Aniket Sahrawat

If you are using Java 8 you can do it in the following way:

如果您使用的是 Java 8,则可以通过以下方式进行:

Integer sum = IntStream.range(1, 1000) // create range
                  .filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
                  .sum(); // output: 233168

To count the numbers which are divisible by both 3and 5twice you can either write the above line twice or .map()the 2 * ivalues:

要计算这是整除两个数字3,并5两次,你可以写上线两次或两次.map()2 * i值:

Integer sum = IntStream.range(1, 1000)
                  .filter(i -> i % 3 == 0 || i % 5 == 0)
                  .map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
                  .sum(); // output: 266333