0

Write a program to find a prime number between 2 numbers using call function

#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<<endl; } } return 0; }

19th Feb 2021, 10:17 AM
soni singh
soni singh - avatar
2 Respuestas
+ 7
In you isPrime() function, you are iterating till the number itself, and (num%num) will always equate to zero. Simple fix Change "<= num" to "< num" to get desired output https://code.sololearn.com/c3bonIZTGz87/?ref=app optimised fix: you don't even have to iterate till num-1 to check if the number is prime or not, you can also check untill (num/2) or better (sqrt(num))
19th Feb 2021, 10:22 AM
Arsenic
Arsenic - avatar
+ 2
Yeah it's working thanks 😁
19th Feb 2021, 10:25 AM
soni singh
soni singh - avatar