Reputation: 64
#include <iostream>
using namespace std;
bool isPrime(int num){
for(int i=2;i<=num;i++){
if(num%i==0){
return false;
}
}
return true;
}
int main()
{
int a,b;
cin>>a>>b;
for(int i=a;i<=b;i++){
if(isPrime(i)){
cout<<i;
}
}
return 0;
}
Please tell me my mistake, program is running successfully but not printing anything.
Upvotes: 1
Views: 393
Reputation: 1
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int num) {
if (num <= 1) return false; // 0 and 1 are not primes
if (num <= 3) return true; // 2 and 3 are primes
if (num % 2 == 0) return false;
for (int i = 3; i <= sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}
int main() {
int a, b;
cout << "Enter two integers (a < b): ";
cin >> a >> b;
if (a >= b || a < 2) {
cout << "Invalid input. 'a' should be less than 'b' and greater than or equal to 2." << endl;
return 1;
}
cout << "Prime numbers between " << a << " and " << b << " are:" << endl;
for (int i = a; i <= b; ++i) {
if (isPrime(i)) {
cout << i << " ";
}
}
cout << endl;
return 0;
}
Upvotes: 0
Reputation: 1
bool isPrime(int num){
if(num<2){
return false;
}
else {
int x = num/2;
for(int i=2;i<=x;i++){
if(num%i==0){
return false;
}
}
}
return true;
}
Upvotes: 0
Reputation: 18
for(int i=2;i<num;i++)
you've used i<=num where the logic should be i<num in your isPrime function. cause all the primes are divided by themselves. but you should not count that while finding primes
Upvotes: 0
Reputation: 24062
The problem is you're checking all divisors from 2
to num
, inclusive. Since every positive integer divides itself, you're not finding any primes. The minimal fix is to change the loop exit condition to exclude num
:
for(int i=2;i<num;i++)
Note that this will work, but it's very inefficient. Here's a much faster version. This version also rejects anything less than 2, since 0 and 1 aren't prime:
bool isPrime(int num){
if (num < 2){
return false;
}
if (num == 2){
return true;
}
if (num % 2 == 0){
return false;
}
for (int i=3; i*i<=num; i+=2){
if(num%i==0){
return false;
}
}
return true;
}
This version makes a special case check for 2
, and for even numbers. After that, it only checks for odd divisors. Once the divisor exceeds sqrt(num), it can stop (the loop exits when i*i > num
).
Upvotes: 3