Home > Software engineering >  How do I convert for loop to while loop in a method?
How do I convert for loop to while loop in a method?

Time:11-16

I am trying to convert a for loop method to a while loop method.

static boolean isPrime(int n)
   {
       for(int i = 2 ; Math.pow(i, 2) <= n ; i  )
           if(n % i == 0)
               return false;
       return true;
   }

I got this so far but when It prints I output different numbers. What am I missing?

static boolean isPrime(int n)
   {
      int i = 2;
      while (Math.pow(i, 2) <= n)
      {
         i  ;
         break;
      }
      if(n % i == 0)
         return false;
      return true;
   }

CodePudding user response:

Remove break in your while loop, and put if check inside while loop.

public boolean isPrime(int n)
{
    int i = 2;
    while (Math.pow(i, 2) <= n)
    {
        if(n % i == 0)
            return false;
        i  ;
    }
    return true;
}

CodePudding user response:

You should put the if statement checking for n%i == 0 inside the while, not outside

  • Related