write the prime no program in c++?

Answer Posted / prateek

I found some good and new ways to write this programe.
Thankx to all. Well even I have also tried to make this
programe. By making use of "while loop";

#include<iostream>
#include<conio.h>

using namespace std;

void main(){

int num,n,i=0,flag=0;;
cout<<"Enter the number";
cin>>num;

n=num/2;
while(i<n)
{
++i;
if(num%i==0 && i!=1)
{
flag=1;
break;
}
else
{
flag;
}
}
if(flag)
{
cout<<"The number is not a prime number";
}
else
{
cout<<"The number is a prime number";
}

getch();


}

Plz notice, that I have divided the number by 2. Suppose
user input 42. The highest divisible value of 42 will be
its half, i.e., 21(21*2=42). So there is no need to check
the loop condition until the value of 'i' reach num. Becoz
it is for sure, that the values more than its half are not
divisible. This will increase the efficiency of the
programe.

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is atoi in c++?

564


Can class objects be passed as function arguments?

601


What is the arrow operator in c++?

558


What is code reusability in c++?

664


What is pointer to array in c++?

615






What is c strings syntax?

607


What is late binding c++?

538


What is the difference between while and do while loop?

554


Which c++ compiler is best?

584


What are stacks? Give an example where they are useful.

592


Is c++ low level?

576


What does new return if there is insufficient memory to make your new object?

582


What is function overloading in C++?

725


How the delete operator differs from the delete[]operator?

642


How to give an alternate name to a namespace?

590