Primal number algorithm: works for small numbers (<100000 or so) and then fails

I made a code to determine whether a number is prime or not. I doubt it's optimized, but that's not what's interesting. Thing is, this code works for numbers up to around 10^7, with 10^9 being described as a prime number which it obviously isn't. Thoughts on reason?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
  #include "../std_lib_facilities.h" //include definitions

int main()
{
	int n = 1;
	int x = 2; //x starts at 2 because prime numbers are all div. by 1
	cout << "enter a number\n";
	cin >> n;
	if (n % 2 == 0 || n % 3 == 0) // number divisible by 2 or 3?
	{
		cout << "not prime number\n";
		keep_window_open();
		return 0;
	}

	else
	{
		if (n % 5 == 0 || n % 7 == 0) // number divisible by 5 or 7?
		{
			cout << "not prime number\n"; 
			keep_window_open();
			return 0;
		}
		else
		{
			while (x < n) //check if divisible by all numbers below
			{
				if (n % x == 0)
				{
					cout << "not prime number\n";
					keep_window_open();
					return 0;
				}
				else
				{
					x++;
				}
			}
			cout << "prime number\n";
			keep_window_open();
			return 0;
		}
	}
}

tl:dr for code: check if number divisible by 2 or 3, then by 5 or 7, then if number passes all those check all numbers beneath it. If it passes that, print that it's a prime number.
It seems to be working for me.

C:\Users\Michael\Programming\cplusplus.com\random\p2>a
enter a number
1000000000
not prime number

C:\Users\Michael\Programming\cplusplus.com\random\p2>a
enter a number
1000000007
prime number

Have you considered any overflow problems?

BTW, you can significantly decrease the amount of time it takes by checking

26
27
while (x <= sqrt(n))
{

Do you have specific numbers for which it fails?
Last edited on
Thank you for the pointing out the sqrt possibility, I forgot about that.
10^10 causes the prime number thing my bad didn't count the zeroes properly.
And I guess it's overflow-that explanation makes sense. Thank you.

Last edited on
Yes, 1010 is overflow for int.

Since negative numbers cannot be prime, you might as well use unsigned long long int as your type. Then you'll be able to use numbers over 1018.

Hope this helps.
Topic archived. No new replies allowed.