using namespace std;
//I tried this but it does not run. How should I check guess is prime number or not?
bool isprime(int guess)
for (int i=0; i<=guess; i++)
if((guess%i != 0)||(i != 0)||(i!=guess))
const int limit = 5;
for(attempt = 0; attempt < limit; attempt++)
cout<<"Please enter any Prime number brtween 1 to 100. You have "<<(limit-attempt)<<" attempts remaining"<<endl;
> int guess;
if(attempt == limit)
> Improve solution Permalink Posted 41 mins ago
Ehtisham Ul Hassan
Have a Question or Comment?
Add your solution here
So Ehtisham, I suggest you work through your code with a test value, say 7 which we know is a prime.
In isprime() argument guess is 7, and when i=0, the condition (i!=guess) is true so the function returns false; not a good start
You need to modify your test(s), and check them by hand until you are happy they give the correct result for a few known primes and non-primes. For starters, you don't know if a number is prime or not until you have tested for division by all numbers in the for() range, so I don't think you can return true inside the loop.
There is more wrong with your loop. Don't start by dividing by 0 (see lines 4‑5 in Junilu's post). Don't loop up to ≤ i, which is an out by one error. Work out how many times the loop will executed.
Anyway, you don't need to test all numbers to see whether they divide into a number. You need to test prime numbers ≤ √i. Even if you don't have a supply of prime numbers to iterate, you can use 2 and then all subsequent odd numbers. That will speed up execution a lot.
The for-loop isn't guaranteed to execute at all so there's a possibility that execution will not go through the if-else statement inside the for-loop and hit one of the return statements. In that case, there is no statement after the for-loop that would return a boolean value. Unlike with Java which would produce a compile-time error, C/C++ is more permissive and will let that code compile. I don't know what happens at runtime though if the for-loop doesn't execute at least one iteration.
The best ideas are the crazy ones. If you have a crazy idea and it works, it's really valuable.—Kent Beck