Darthfett
Aerospace/Cybersecurity Software Engineer
- Reaction score
- 615
I'm a bit confused. How would I find the square root of the number?
I haven't tested, but basically you swap out y <= x/2 with y <= sqrt(x). If you understand patterns, you would know that if you start comparing non-prime numbers factors from 1 to the number, you will start repeating the factors after you hit sqrt(n).
For example, lets say you have 16. Factors:
sqrt(16) = 4
16 = 1 * 16
16 = 2 * 8
16 = 4 * 4
16 = 8 * 2
16 = 16 * 1
After 4 (or sqrt(n)), you can stop checking the numbers, because if you know that 1, 2, and 4 are factors of 16, you also know that 16/1, 16/2, and 16/4 are also factors of 16. You don't need to do the rest of the numbers.
Fixed, untested code:
Code:#include <iostream> #include <cstdlib> #include <cmath> using namespace std; int isPrime(int x); int main () { int input; int count; int y; cout<<"Please, enter a number: "; cin>>input; if (isPrime(input)==1) { cout<<"Your number is already prime.\n"; return 0; } for (count=input; y!=1; count++) { if (isPrime(count)==1) { cout<<"The next prime number is "<<count<<".\n"; y=1; } } cin.get(); return 0; } int isPrime(int x) { int y; for (y=2; y<=sqrt(x); y++) { if (x%y==0) { return 0; } } return 1; }
Yes, that's true. A further optimization, as suggested by Dave, would be to check for only odd numbers (after checking that n is not 2, of course)
I think you're thinking of the different situation, of finding prime numbers, in that you loop from 3 to n, increasing the iterator by 2. In this case, he's trying to see if a specific number is prime. A simple x % 2 operation will eliminate all even numbers.