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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check to see if a user entered number is relatively prime 1

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi, how can I check to see if a user entered number is relatively prime?

Any help appreciated.
 
Try

bool isPrime(long lnPassed)
{
double nRoot = sqrt(lnPassed);
for (long i = 2; i <= nRoot; i++)
{
if (lnPassed%i == 0)
{
return false;
}
}
return true;
}
 
The above method can be quite slow for large numbers.

Another method would be to run the above function once for all numbers up to some large value, and save the prime values into a file. Then in your program, store the values into an array, and then only try the mod function (%) where i is a prime. Will be quicker at runtime, but memory usage will be higher.

eg

bool IsPrime(long lngNumber)
{
double dblUpperBound = sqrt(lngNumber);

//the following line is pseudocode-esque.
//Populate the array however you want
long KnownPrimes[] = 2,3,7,11 etc...;

int i = 0;

while((KnownPrimes<=dblUpperBound) && (i < SizeOfKnownPrimesArray))
{
if(lngNumber % KnownPrimes == 0)
return False;
i++
}
return true;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top