Reputation: 13
I would like to have a program that show range in specific range and show "no primes" once only if there is no primes in that range like 24 to 28.
int count=0;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
count=0;
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0)
count++;
}
if(count==0)
System.out.println(prime);
}
if (count>0)
System.out.println("nope");
I have tried to put
if (count>0)
System.out.println("nope");
outside the loop,however it also prints when the range having primes. How can i tackle it?
Upvotes: 1
Views: 133
Reputation: 10784
You could design a function to determine if a number is prime something like:
//checks whether an int is prime or not.
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
and within a for loop, you call the function to each element of the interval:
for(int i=lowerLimit;i<=upperLimit;i++){
if (!(isPrime(i))){
System.out.println("nope");
break;
}
}
Sorry if I have some syntactic errr, I replied from the cell phone.
Upvotes: 2
Reputation: 3816
First of all, your method for detecting primes is terrible. It works, but it's super slow. I'd suggest you look into using sieves if you want to improve that inner loop.
Secondly, what exactly are you trying to count? Right now your count variable stores the amount of divisors a number has, and then you set it to zero when you check the next number. How is that going to tell you anything about how many primes you have in a certain range? You can just do something like this:
notPrime = false;
for(prime = lowerLimit ;prime < upperLimit; prime++)
{
for(divisor = 2; divisor <prime; divisor++)
{
if(prime % divisor== 0){
notPrime = true;
break;
}
if(notPrime)
break;
}
if(notPrime) System.out.println("There's a prime");
Upvotes: 2
Reputation: 41230
Keep one extra variable like noOfPrime
, which will count the number of prime number with in a range. And increase by 1 if you found any prime, so that out side of loop you could determine the number prime number as well there is any prime number or not.
int count = 0;
int noOfPrime = 0;
...
for(prime = lowerLimit ;prime < upperLimit; prime++){
...
if(count==0){
System.out.println(prime);
noOfPrime+=1;
}
}
if(noOfPrime >0)
System.out.println("no primes);
Upvotes: 2
Reputation: 3896
Everytime you get to the end of the outer loop and count
is still 0, it means that you've found a prime number. So if this happens even once, then you're not going to print "nope" at the end. Use a boolean
variable to keep track of whether or not you've seen a prime. Since this is homework, I'll let you figure out exactly how to use it. Hint: declare the boolean
above both loops.
Upvotes: 0