Skip to content
Advertisement

Need help to calculate the sum of numbers by omitting somes of them

#1. I need to write a Java program that calculates the sum of numbers from 1 through 10,000 (including 1 and 10,000) but omitting numbers that are divisible by three and numbers whose hundred digit is 2 or 3 (for example 8200 or 5312).

I begin with but didnt work:

public class Sum10000 {

    public static void main(String[] arg) {
        long i = 0;
        long sum = 0;

        while (i != 10000) {
            sum = sum + i;
            i++;

            if ((i % 3) == 0 || (i >= 200 && i <= 399) || (i >= 1200 && i <= 1399)
                    || (i >= 2200 && i <= 2399) || (i >= 3200 && i <= 3399) || (i >= 4200 && i <= 4399)
                    || (i >= 5200 && i <= 5399) || (i >= 6200 && i <= 6399) || (i >= 7200 && i <= 7399)
                    || (i >= 8200 && i <= 8399) || (i >= 9200 && i <= 9399)) {
                continue;
            }
            System.out.println( i);
            System.out.println(sum);

        }
    }
}

Advertisement

Answer

You should only increment the sum after testing the condition.

while (i != 10000) {
    i++;
    if ((i % 3) == 0 || (i >= 200 && i <= 399) || (i >= 1200 && i <= 1399) ||
        (i >= 2200 && i <= 2399) || (i >= 3200 && i <= 3399) || (i >= 4200 && i <= 4399) ||
        (i >= 5200 && i <= 5399) || (i >= 6200 && i <= 6399) || (i >= 7200 && i <= 7399) ||
        (i >= 8200 && i <= 8399) || (i >= 9200 && i <= 9399)) {
        continue;
    }
    sum += i;
    System.out.println(i);
    System.out.println(sum);
}

Using a Stream can simplify this:

System.out.println(IntStream.rangeClosed(1, 10000)
  .filter(x -> x % 3 != 0 && x / 100 % 10 != 2 && x / 100 % 10 != 3).sum());
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement