Prime Number Function

Apr 6, 2015 at 3:24pm
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;
}
Apr 6, 2015 at 3:33pm
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 Apr 6, 2015 at 3:38pm
Apr 6, 2015 at 3:40pm
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.
Apr 6, 2015 at 3:45pm
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 Apr 6, 2015 at 3:45pm
Apr 6, 2015 at 4:02pm
It wasnt meant offensive. Sorry.

it's ok.

something is off. your program outputs some of the non prime numbers too, like 21 etc
Apr 6, 2015 at 4:13pm
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 Apr 6, 2015 at 4:15pm
Apr 6, 2015 at 4:20pm
I think it's still not right in 1 to 10
Apr 6, 2015 at 4:21pm
i <= sqrt(number)
Apr 6, 2015 at 4:25pm
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)
Apr 6, 2015 at 4:34pm
great! it works. Thank you so much :)
Topic archived. No new replies allowed.