Prime Number Function

Hello,
My code doesn't give the output, prime numbers 1-100. What have I done wrong?


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
#include<iostream>
#include<cmath>
using namespace std;

int n, i;

bool isPrime(int number)
{
	for (i = 1; i <= sqrt(n); i++)
		n = n / i;
	if (n / i == 0)
		return false;
else return true;
}

int main()
{
	for (i = 1; i <= 100; i++)
	{
		if (isPrime(i)==true)
			cout << i<<endl;
	}
	system("pause");
	return 0;
}
Are you expecting the program to magically know what "n" is equal to? because you never tell the program what n is equal to.

Edit: Try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
bool isPrime(int number)
{
	bool prime = true;
	for (int j = 2; j*j <= number; j++)
	{
		if (number % j == 0)
		{
			prime = false;
			break;
		}
		return true;
	}
}

int main(){

	for (int i = 2; i<500; i++)
	{
		if (isPrime(i) == true)
			cout << i << endl;
	}
	system("pause");
	return 0;
}
Last edited on
i see, so it should change to bool isPrime(int n)
But then the program gives an error.
btw your words are a bit offensive.
btw your words are a bit offensive.

It wasnt meant offensive. Sorry.

i see, so it should change to bool isPrime(int n)

No not that n. This n int n, i; Here you create n. But then you do this
for (i = 1; i <= sqrt(n); i++)

sqrt(n); But n has no value, its currently garbage becuase you only created the variable n, but never gave it a value.

Read the code Ive provided, it gives you the first 500 prime numbers, you only have to change the for-loop if you want 1000.
Last edited on
It wasnt meant offensive. Sorry.

it's ok.

something is off. your program outputs some of the non prime numbers too, like 21 etc
Oh ye lol. Just noticed. Try this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool isPrime(int number)
{
	for (int i = 2; i < sqrt(number); i++)
	{
		if (number%i == 0)
		{
			return false;
		}
	}
	return true;
}

int main(){

	for (int i = 2; i<500; i++)
	{
		if (isPrime(i) == true)
			cout << i << endl;
	}
	system("pause");
	return 0;
}
Last edited on
I think it's still not right in 1 to 10
i <= sqrt(number)
Its supposed to start at 2, not 10. So 2-10. Yeh still not quite correct, forgot one thing.

Add a +1 in the sqrt.

for (int i = 2; i < sqrt(number + 1); i++) // added (number +1)
great! it works. Thank you so much :)
Topic archived. No new replies allowed.