The objective of this program is to determine whether a number is prime or not. I've read the program through over and over but for whatever reason, the output is the same whether the number is prime or not. I figured out that the problem is in this snippet of code but I can't figure out the error.
while (ctr<=n)
{
rem=n%ctr;
if (rem=0.0)
mult++;
ctr++;
}
#include <iostream>
using namespace std;
int main()
{
int mult=0, ctr=1, n;
double rem;
do
{
cout<<"Input a number greater than 1: ";
cin>>n;
if (n<=1)
{
cout<<"\nInvalid input!"<<endl;
cout<<"Please try again! :)\n"<<endl;;
}
}
while (n<=1);
cout<<"\n";
while (ctr<=n)
{
rem=n%ctr;
if (rem=0.0)
mult++;
ctr++;
}
if (mult>2)
cout<<"The number is not prime.";
else
cout<<"The number is prime.";
cout<<"\n\n";
system("pause");
return 0;
}
Could you use [ code ] [ / code ] (without the spaces) tags instead of the program output tag?
It makes the code look so much prettier...
Anyways, "rem" doesn't need to be a double.
You're never going to get anything other than an integer with the modulus operator....
And then if (rem=0.0)
should be if (rem == 0) // Only works if "rem" isn't a floating-point type!
because the comparison operator is == (two equal signs), not = (one equal sign), which is the assignment operator...
When you go to post, on the right side (or bottom), there will be something that says format. Mouse over those things and you'll see one that says Source code
I wouldn't call what you linked to a "good and efficient" program, Fahadmunir32. In fact it's not C++ (because main can't have a void return type in C++) and it is quite probably the most naive and inefficient method for checking a prime that I've seen. Not to mention the use of unnecessary and non-portable console functions and deprecated headers.
Cire i said "good and efficient program " about not the link i posted but about the program above..
The link i posted its easy to understand for me..
but this site is really helpful.. i bookmarked.. :)
fahadmunir32 your logic are good if you want to determine if one number are prime or not.
But you could change for(int a=1;a<=number;a++)
to for(int a=2;a<=number;a++)
and if(count==2)
to if(count==1)
because all the numbers will be divided by 1. Therefore unnecessary to check.