Jason arora
Jason arora

Reputation: 550

Output of finding prime numbers between given range does not come as expected

Given two numbers n1 and n2 as input, count the primesnos containing all the primes between n1 and n2.

MyApproach

I took 2 for loops.For each element from start to stop I checked whether the elements are prime or not and incremented their count.

public int getPrimes(int start,int stop)
{

  int countprime=0;
  boolean b1=true;
  for(int j=start;j<=stop;j++)
  {
      for(int i=2;i<=j/2;i++)
      {
          if(j%i==0)
          {
              b1=false;
              break;
          }
      }
      if(b1==true)
      countprime++;
  }

 return countprime;

 }

 Parameters         Actual Output   Expected Output

 '6,11'                  0           2

Upvotes: 1

Views: 70

Answers (2)

mazhar islam
mazhar islam

Reputation: 5619

For each value of j from the outer loop, you need to re-initialize b1 = true. Because whenever you found j is not prime, you set your flag b1 to false and you never reset it. So if j is a prime for any next iteration, if (b1 == true) will not find a true path as b1 is already set to false. Hence, countprime is not going to increment.

So do the following:

for(int j=start;j<=stop;j++)
  {
      b1 = true;
      for(int i=2;i<=j/2;i++)
      //rest of your codes...

Side note: Instead of i <= j/2, i <= sqrt(j) can make your code more faster! Besides, you may also read Sieve of Atkin.

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26077

Need to reset value of variable b1

b1 = true;

Code

public static int getPrimes(int start, int stop) {
        int countprime = 0;
        boolean b1 = true;
        for (int j = start; j <= stop; j++) {
            b1 = true;
            for (int i = 2; i <= j / 2; i++) {
                if (j % i == 0) {
                    b1 = false;
                    break;
                }
            }

            if (b1 == true)
                countprime++;
        }
        return countprime;
    }

Upvotes: 1

Related Questions