Project Euler #1 in Java

前端 未结 8 1634
旧时难觅i
旧时难觅i 2021-02-04 18:22

I\'m having problems with this code. I don\'t want to look at others, so I\'m wondering what\'s wrong with mine.

If we list all the natural numbers below 10 that are mu

8条回答
  •  青春惊慌失措
    2021-02-04 18:58

    If a number is a multiplier of both 3 and 5 (e.g.: 15, 30, 45, etc.), you will count it twice. So instead of two for loops, you should have one, with a complex condition:

    public class Multiples {
        public static void main (String [] args) {
        int temp = 0;
    
        for (int i = 0; i < 1000; i++) {
            if (i % 3 == 0 || i % 5 == 0) {
                temp = temp + i;
            }
    
        }
    
        System.out.println (temp);
       }
    }
    

提交回复
热议问题