After that, we divide the number by every integer greater than 1 and less than the number itself.
If the remainder in every case is non-zero, the number is prime.
(we could reword the above, if the remainder in any case is equal to zero, the number is not prime)
That's all.
As a refinement, it is possible to improve the efficiency by testing the remainder when dividing by integers up to and including the square root. But care needs to be taken to avoid calling the square root function repeatedly for the same number - that could reduce or negate any efficiency gains.
Implementation of Chervil's specification with usage example: on run, program takes positive integer (0<=n<=4294967295) input from user and checks if prime, then outputs appropriate statement.
#include <iostream>
#include <math.h>
#include <cmath>
usingnamespace std;
int main(){
float square;
int a = 0;
bool correct = 1;
while( a != -1 ){
cout << "Enter number [press -1 to exit] : ";
cin >> a;
for( int i = 2 ; i < a ; i++ ){
if ( a % i == 0 ){
correct = false;
break;
}
if( correct != false )
correct = true;
}
if( correct == true )
cout << a << " is a prime number ! " << endl;
elseif ( a == 1 || a == 0 || correct == false)
cout << a << " is not a prime number ! " << endl;
else
cout << a << " is not a prime number ! " << endl;
cin.clear();
cin.ignore(100,'\n');
correct = 1;
}
system( "pause" );
return 0;
}
Hey guys thanks for all of your guidance , i do this source code that working well but has a little problem ... when it print the result ,print it forever without stop ... so how can i stop it?
#include <iostream>
usingnamespace std;
int main()
{[output][/output]
int x , i = 2;
cout << " Enter a number : " ;
cin >> x;
while (x !=0)
{
if (x <= i)
cout << " The number u entered is Prime " ;
elseif (x > i && x % i==0)
cout << " The number u entered is Composite ";
cout << endl;
if (x > i && x % i!=0)
i++;
if (x==1)
cout << " the number is neither prime or composite" ;
}
cin.get();
cin.get();
}
@lvlichael72
You created an infinite loop. the condition while (x !=0) never changes once the loop has been entered, since x doesn't change.
There are at least three ways to fix this. One would be to change the loop condition itself, to depend on something which does change, such as the integer i, which is the only thing that changes. Another would be to change a value such as this x=0; within the loop to make the condition false when you want to exit. Lastly you could use the break; statement which is used to exit from various types of control structures.
But still, your code is quite complex and messy. In effect you are implementing a version of this:
1 2 3 4 5 6 7 8 9 10 11 12 13
bool isPrime(int x)
{
if (x==1)
returnfalse;
int i=2;
while (i < x)
{
if (x%i == 0)
returnfalse;
i++;
}
returntrue;
}