George Poyilil George Poyilil - 6 months ago 6
Java Question

Why this program is not working?

I'm trying to write a program to sum all the integers between 1 and 1000, that are divisible by 13, 15 or 17, but not by 30. The code i tried is given below. I'm getting in a loop which prints sum=0 again and again forever. Please help!

package project;

public class div13n15n17not30 {

int sum=0;

int num=0;


while(num<=1000){

if(num%13==0||num%15==0||num%17==0 ){

if(num%30!=0){
sum=sum+num;
++num;
}
}

System.out.println("Sum = "+sum);
}

}
}

Answer

Try Something like below:

    public static void main(String[] args) {
    int sum = 0;

    int num = 0;

    while (num <= 1000) {

        if (num % 13 == 0 || num % 15 == 0 || num % 17 == 0) {

            if (num % 30 != 0) {
                System.out.println("here" + num);
                sum = sum + num;
            }
        }
        ++num;

    }
    System.out.println("Sum = " + sum);

}
Comments