prime number generator

i wrote a progam that generates prime numbers up to a certrain number with certain amount of iterations,the code is included below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream.h>
int main()
{
    long int num,lim,ite,c;
    cout<<"Prime number generator"<<endl;
    c=2;
    num=1;
    cout<<"enter number of iterations";
    cin>>ite;
    cout<<"enter limit";
    cin>>lim;
    while(num < lim)
    {
    while(c <= ite)
    {
            if(num%c != 0){c++;if(c == ite){cout<<num<<endl;c=2;num++;}}
            else{num++;}
    }
}
    system ("pause");
    return 0;
}

it starts an infinite loop,ideas?
Last edited on
1
2
3
while(c <= ite)
/*...*/
if(c == ite){/*...*/c=2;
c will never be larger than ite which is loop ending condition.
Please organize your code. I don't know what you're trying to do. Could you give a sample of what do you expect the output will be?

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

int main()
{
    long int num,lim,ite,c;
    cout<<"Prime number generator"<<endl;
    c=2;
    num=1;
    cout<<"enter number of iterations";
    cin>>ite;
    cout<<"enter limit";
    cin>>lim;
    while(num < lim)
    {
	while(c <= ite)
	{
		if( num%c != 0 )
		{
		   c++;
		   if(c == ite)
		   {
		      cout << num << endl;
		      c=2;
		      num++;
		    }
		}
		else
		{
		   num++;
		}
				
	}
}
    system ("pause");
    return 0;
}
Last edited on
To Minipa: you are not wrong but that is not the cause of the infinite loop, the first loop iswhile(num < lim)and in line 16 of the first post {cout<<num<<endl;c=2;num++;}
To Croco: expected output is : 1,5,7,11,13.......1997,1999. if lim=2000
Last edited on
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
#include <iostream>

bool isPrime(const int& num)
{
	if ( num < 2 )
		return false;

	for(int a = 2 ; a < num ;a++)
     {
        if( num % a == 0 )
        {
             return false;
        }
     }
	return true;
}

int main()
{
    int number;
	std::cout << "Enter your number ";
	std::cin >> number;
	
	for (int i = 0; i < number; i++)
	{
		if ( isPrime(i) )
			std::cout << i << " ";
	}
	std::cout << std::endl;
	std::cin.get();
    return 0;
}
the first loop iswhile(num < lim)
This condition will never be checked because inner loop is in infinite cycle.
whats the purpose of the num variable? im a bit confused with its purpose in this program
Topic archived. No new replies allowed.