Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a c/c++ function that determines if a given number is a prime

Status
Not open for further replies.

bitshifter05

Programmer
Jul 15, 1999
13
0
0
US
I have a program that is for school and part of it is to determine if a given number is a prime. I have tried to look for a formula that gives me this answer. No such luck. I know that the only even prime is 2. But other than that I don't wan't to have to check the given number against the whole prime table. Thanks for any help.

bitshifter [sig][/sig]
 
First things first, you're correct the only even prime is 2, so how can you use that as your checking method.

I'll give you a hint.

result = primetest % 2

What is "%"?
Once you've looked that up. What should "result" be?

Any more then that and I've done it for you.

:)

B [sig][/sig]
 
Thanks anyway brainism, I figured it out on my own the code to determine if a number is a prime number is as follows...

string Prime(int IntValue) // returns string "Yes" or "No"
{ string outstring;
if(!(IntValue % 2))
{ if(IntValue == 2)
outstring = "Yes";
else
outstring = "No ";
}
else
{ for(int i =3; i <= (sqrt(IntValue) + 1); i = i +2 )
{ if(!(IntValue % i))
{ outstring = &quot;No &quot;;
i = IntValue;
}
else
outstring = &quot;Yes&quot;;
}
}
return outstring;
} [sig][/sig]
 
Hei, you are wrong at the same beginning.You need to do like this:
for(int i=3;i<=((IntValue/2)+1);i++)
{
if(!(IntValue%i))
{
outstring=&quot;No&quot;;
return outstring;
//i=IntValue;why do you need it?
}else if(i>(IntValue/2))
{
outstring=&quot;Yes&quot;;
}
}
 
All previous ansvers are based on Euklidian Seed algorithm. It has a drawback of low speed. The last answer from JohnFill would if you change the condition in for-loop from IntValue/2 to sqrt(IntValue) -- you'll get more efficient code with the same result. If you want to check for primality large numbers you should use probably tests, that's the only way. Look for them in Schneier's books and in Cryptography issues.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top