### CODE TO FIND PRIME NUMBERS NOT WORKING

Hi there, the code below is suppose to output all the prime numbers between the values of startNum and endNum variables. but its not working correctly instead it display all the numbers between startnum and endNumber including non-prime numbers. please help.
 ``123456789101112131415`` ``````void PrimeFinder::run() { bool isPrime = false; for(int i = startNum; i <= endNum; i++) { for(int j = 2; j < i; j++) { if((i % j) == 0) isPrime = false; else isPrime = true; } if(isPrime == true){emit foundPrime(i);} } }``````
 ``123456789101112131415161718192021`` ``````void PrimeFinder::run() { bool isPrime = false; for(int i = startNum; i <= endNum; i++) { for(int j = 2; j < i; j++) { if((i % j) == 0) { isPrime = false; std::cout << i << " is not a prime\n" ; } else { isPrime = true; std::cout << i << " is a prime\n" ; } } if(isPrime == true){emit foundPrime(i);} } }``````

What do you think the output will be?
Last edited on
the code doen't work, if i test the numbers between 9 and 30 it starts at 17 by displaying it ten time and then it says 18 is prime two times and two more times it says 18 not prime and so on...

 ``1234567891011121314151617181920212223242526`` ``````#include using namespace std; int main(int argc, char** argv) { bool isPrime = false; for(int i = 9; i <= 30; i++) { for(int j = 2; j < i; j++) { if((i % j) == 0) { isPrime = false; std::cout << i << " is not a prime\n" ; } else { isPrime = true; std::cout << i << " is a prime\n" ; } } } return 0; }``````
> if i test the numbers between 9 and 30 it starts at 17
scroll.

> the code doen't work,

`if(isPrime == true)`¿why are you comparing a boolean value against `true'? it will give you a boolean value (that you think you should compare against `true')
((isPrime==true) == true) == true ...
this doesn't work either

 ``12345678910111213141516171819202122232425262728`` ``````#include using namespace std; int main(int argc, char** argv) { bool isPrime = false; for(int i = 9; i <= 30; i++) { for(int j = 2; j < i; j++) { if((i % j) == 0) { isPrime = false; //std::cout << i << " is not a prime\n" ; } else { isPrime = true; //std::cout << i << " is a prime\n" ; } } if(isPrime){cout << i << " is a prime number" <
Again, your prime definition is wrong.
Consider http://en.wikipedia.org/wiki/Rubber_duck_debugging
 the code doen't work,

The code works just fine. It's the algorithm that doesn't work.

The code just does what it was told to do. It was my hope that by looking at the output of the code with the changes I made, you would realize that the algorithm was wrong.

Get out a pen and pencil and work out how you would do this by hand, then convert that algorithm into code.
Topic archived. No new replies allowed.