Pages

Prime count between two numbers | java

I was facing an algorithm problem where I have to find the total number of integers between two given integer. The two integers (start, end) count be any integer where start < end and they are both positive integers.

So here's what i did.

public static int primeCount(int start, int end){
  
  int count = 0;
  int mod = 0;
 
  firstloop:
  for(int i=start; i<=end; i++){
   
   if(i<=1){
    continue;
   }else if(i==2){
    count++;
    System.out.println(i);
    continue;
   }
   
   //secondloop:
   for(int j=2; j<=(int)(i/2); j++){
    mod = i % j;
    //System.out.println(i + "%" + j + " = " + mod);
    if(mod==0){
     //count++;
     //System.out.println(i);
     continue firstloop ;
    }
   }
   count++;
   System.out.println(i);
  }
  
  return count;
 }

one interesting thing here what is used is the labeled break continue feature of java which even many experienced professionals do not normally remember. You count specify the label in the break or continue statement to target which for loop you want to break or continue.

So you learned new thing. Enjoy..

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...