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

前端 未结 12 1059
我在风中等你
我在风中等你 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:46

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

    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.

提交回复
热议问题