0

So I'm learning Java by myself and I would like to create a program that returns the divisors of a number N in a given interval [A, B]. Here's my code

Scanner in = new Scanner(System.in);
        int n, a, b;

System.out.print("A: ");
        a = in.nextInt();

System.out.print("B: ");
    b = in.nextInt();

System.out.print("N: ");
    n = in.nextInt();

System.out.printf("The divisors of %d in the interval [%d, %d] are: ", n, a, b);

    for (int i = 1; i <= n & i < b; ++i){
        if (n % i == 0){
            System.out.println(i + " ");
        }
    }

Here's the problem: when I put a < i & i < b in the for condition, the program doesn't work. I've read it that Java is short-circuiting, but can I fix my code or should I use a while or something like that?

2 Answers 2

1

The logical AND operator in Java is &&, not &, the latter which is the bitwise AND operator. But, you don't even need the condition a <= i && i <= b, because you can simply initialize the loop variable to a:

for (int i=a; i <= b; ++i) {
    if (n % i == 0) {
        System.out.println("Found divisor: " + i);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Tim's answer above is a great answer, but you also asked about if you could/should do this as a while loop. If you wanted to use a while loop, a simple implementation would be

while (a <= b) {
    if (n % a == 0) {
      System.out.println("Found divisor: " + a);
    }
    a++;
}

Comments