URGENT : How to check whether number is prime or not

then how are you gonna do the exams/labs mate?

the easy way out now could come back and bite you in the @$$ later.. so watch out

dunno if this works... got it off google :D

Code:
#include<iostream.h>
#include <math.h>

void main()
{
	int number;
	cout<<" ---------------------------------------------"<<endl;
	cout<<" Enter a number to find if its a prime number "<<endl;
	cout<<" ---------------------------------------------"<<endl;
	cin>>number;
	bool a =true;
	for(int i=2;i<sqrt(number);i++)        //check untill the square root
	{
		if(number%i==0)            // if it is divisible it is non prime 
		{
			a=false;
			break;
		}
	}
	if(a==false)
	cout<<number<<" is not a prime number"<<endl;
	else
	cout<<number<<" is  a prime number"<<endl;

}

Source
 
That's a bit complicated.

Here's wat i've got till now - theres small prob though - ]

#include<iostream.h>

#include<conio.h>

void main()

{

clrscr();

int a,i;

cin>>a;

for (i=2; i<a; i++)

if (a%i==0)

cout<<"not prime";

else

cout<<"prime";

getch();

}
 
This may help you..

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

void main()
{
clrscr();
int a,i;
cin>>a;

for (i=2; i<a; i++)
{
if (a%i==0)
{
cout<<"not prime";
break;
}
else
cout<<"prime";
break;
}
getch();
}
 
#include<iostream.h>
#include<conio.h>

void main()
{
int a,i,check=0;

cin>>a;

for (i=2; i<a; i++)
{
if (a%i==0)
{
check=1;
break;
}
}

if(check==1)
cout<<"Not Prime";
else
cout<<"Prime";

getch();
}

I guess this should work...
 
@akshitmohan,

1)are you new to any sort of programming? Haven't you done anything before, like Qbasic. If you have then just make the code or logic in that and translate it to C++.

2)Else it is too late now, these programs are meant to be done either yourself or in class. How many will you do on the internet a day before?
 
aksit the main part of programming is to make the execution of loop as less as possible.
in my school marks was credits was awarded as marks if u do the program the best possible way.
so just check upto the square root of the number, afterall ur not gonna mug it up right? so how is it tuff?
 
Just iterate de loop half of times the original number... i.e., if a=12, then no number > 7 can be its factor. So, Optimize it, folks!!!
 
Back
Top