Prime number generation in C++


30. C++ program to generate prime numbers up to a limit?

Note: Prime numbers will have only two factors, one factor is the number itself and the other factor is one. Ex: factors of 2 = 1, 2

Program


#include<iostream.h>
#include<stdio.h>
#include<conio.h>
void main()
            {
            int num,flag,i,j;
            clrscr();
            cout<<"Enter the limit:\n";
            cin>>num;
            if(num==1)
            {
            cout<<"No Prime numbers";
            }
            else
            {
            cout<<"Prime Numbers are: \n";
            for(i=2;i<=num;i++)
                        {
                        flag=0;
                        for(j=1;j<=i;j++)
                                    {
                                    if(i%j==0)
                                    flag++;
                                    }
                        if(flag==2)
                        cout<<i<<"\n";
                        }
            }
            getch();
            }

Output

Enter the limit:
15
Prime Numbers are:
2
3
5
7
11
13

No comments:

Post a Comment