Prime numbers help please

I am being asked to generate prime numbers up to an intputted limit from the user. When I input numbers, this program seems to generate number 2 and ODD numbers (both prime and non prime numbers) starting from 3...where did I go wrong?

Also, when I use the same isprime on a different program(which will also be a part of this one) it seems to produce non prime numbers.

BTW, I'm being forced to use functions and arrays

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
45
46
47
48
49
50
51
52
#include <iostream>
#include <cmath>
using namespace std;
int main_menu();
bool isprime(int);
int getprimes(int [], int, int);
int main()
{
	int primes[1000];
	int size, upper, elements;

	size = 1000;
	cout<<"\nEnter the upper limit: ";
	cin>>upper;
	elements = getprimes(primes, size, upper);
	for(int i = 0; i < elements; i++)
		cout<<primes[i]<<' ';

        cout<<'\n';
	system ("pause");
	return 0;

}

bool isprime(int num)
{
	for(int i = 2; i <= num; i++)
	{
		if(num%i == 0 && num != i)
		{
			return false;
			break;
		}
		else
			return true;
	}
}
int getprimes(int primes[], int size, int upper)
{
	int elements = 0;

	for(int i = 0; i < upper; i++)
	{
		if(isprime(i) == true)
		{
			primes[elements] = i;
			elements++;
		}
	}

	return elements;
}
Last edited on
In the isprimes function, you have the return statement in the for loop (within else).
Hence, the function returns a value and exits in the first iteration of the for loop.

You can change this in many ways. I would return a bool which I will set to true initially, and then set to false if the if loop is executed once. return the bool after the execution of the for loop.

However, to find the primes you can also code up the Sieve of Eratosthenes, the simplest of prime number algorithms.
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Topic archived. No new replies allowed.