-1

So I was trying to figure out if the the first iteration in a for loop does not go through the termination condition.

Since when I called it in the main method with an input of 4 IsPrime(4) the for loop still went through. I was expecting it to not go through since i = 2 and n/2 = 4/2 = 2 which will be 2 == 2 which will meet the condition to terminate but it went through and I got the right output but I don't get why it did not fail.

Please help.

public static boolean isPrime(int n){

    if(n <= 1){
        return false;
    }

    for(int i = 2; i <= n/2; i++){
        if(n % i == 0){
            return false;
        }
    }
    return true;
}

2 Answers2

2

Your for loop condition says continue while i <= n/2.

If you start with n == 4 then n/2 == 2. On the first iteration i == 2 so the for loop condition 2 <= 2 is true and it will iterate once.

Then i++ is executed so now i == 3 and fails the condition so there is no second iteration.

Matt
  • 3,677
  • 1
  • 14
  • 24
0

You seem to have a confusion around how for loop works. Let's see the operation on a per-iteration basis :

Iteration 1 :

  • i = 2
  • i <= 2 ? --> True
  • n % i == 0 ? --> 2 % 2 == 0? True
  • return false
  • End of function

Now let's assume your for loop looked something like this :

 for(int i = 2; i <= n/2; i++){
        if(n % i == 0){
            System.out.println("Remainder is 0");
        }
    }

Then the following will the iteration sequence :

Iteration 1

  • i = 2
  • i <= 2 ? --> True
  • n % i == 0 ? --> 2 % 2 == 0? True
  • print --> Remainder is 0
  • i++ --> i = 3 now

Iteration 2

  • i = 3
  • i <= 3 ? --> False
  • Cannot proceed further. For loop condition failed.
  • End of function
Sai Kishore
  • 326
  • 1
  • 7
  • 16
LeoNeo
  • 739
  • 1
  • 9
  • 28
  • Yea I was thinking of the opposite. I was thinking that when the condition was met it will stop the loop. I just realized it was the other way around thanks for the detailed explanation – Hartej Lehal Feb 08 '18 at 04:20
  • glad it helped. It is confusing sometimes :) – LeoNeo Feb 08 '18 at 13:30