C++ PROGRAMS
Prime Numbers are those natural numbers whose factors (which must be natural numbers too) are 1 and the number itself only.
For example: 2, 3, 5, 7, 11, 13, 17, 19, .....
Composite Numbers are those natural numbers which have more than two factors, which include 1 and the number itself also.
For example: 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, .....
Note: 1 is neither prime nor composite number.
In the following program, user will enter any natural number and output will be whether the number is a prime or a composite number. However if user enters any number less than 2 the output will be neither prime nor composite.
In this program I will use for-loop and if statement.
Code:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a,b,i;
cout<<"Prime and Composite Numbers"<<"\n";
cout<<"Enter any natural number: ";
cin>>a;
if(a<2)
cout<<"Neither Prime nor Composite";
if(a>=2)
{
b=1;
for(i=2;i<=a/2;i++)
{
if(a%i==0)
b=0;
}
if(b==0)
cout<<"A composite number";
if(b==1)
cout<<"A prime number";
}
getch();
}
Output:
First Run:
Second Run:
Third Run:
For finding all the prime numbers between any two number, please go through Prime Numbers Between Two Numbers.
For any queries or suggestions please comment !
No comments:
Post a Comment