Hadh - 1 year ago 67
Java Question

# The sum of all the multiples of 3 or 5 below N

I have to find the sum of all the multiples of 3 or 5 below N.
example if we have to list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9,the sum of these multiples is 23.

Now the only problem left is that I want it to be able to read ALL the numbers THEN display the sum, for now it reads one number and display the sum right after it, any ideas?

import java.io.IOException;

public class Solution{
public static void main(String[] args) throws IOException {

int Nbr = Integer.parseInt(line);

for(int j=0; j<Nbr;j++)
{
String[] numbers = new String[Nbr];
numbers[j]= line2;
System.out.println(Somme(Long.parseLong(numbers[j])));
}

}

public static long Somme(long Nn) {
long s = 0;
for (int i = 0; i < Nn; i++) {
if (((i % 3) == 0) || ((i % 5) == 0)) {
s = s + i;
}
}
return (s);
}
}

I suggest you use a Scanner. I would also suggest you add to a sum by iterating from 3 to n in increments of 3. Then from 5 to n in increments of 5 (then exclude the multiples of 3, because they've already been added). Something like

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
int n = scanner.nextInt();
System.out.println(getSum(n));
}
}

public static long getSum(int n) {
long sum = 0;
for (int i = 3; i < n; i += 3) {
sum += i;
}
for (int i = 5; i < n; i += 5) {
if (i % 3 != 0) { // <-- already added if i is divisible by 3
sum += i;
}
}
return sum;
}

Based on your comment below, change main to first read the int of counts, then store them in an array. Something like

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {