ym112
October 26th, 1999, 05:35 PM
i am a rookie programmer who needs help with a program. i have to write a program that when the user enters in an integer, the program has to output all the prime factors of that number. example, if the user inputs 12, the program outputs 1,2,3,12. it does not output 4 or 6 becuase they are not prime numbers. another example: if the user inputs 24, the program outputs 1,2,3,24 but not 4,6,8,or 12 becuase those arent prime numbers. so anyone that can help, please send a reply to ym112@yahoo.com. i would appreciate the help alot. thanks
ALM
October 26th, 1999, 05:50 PM
On 2 samples you give, 12 and 24 shouldn't be outputted either since they're prime, correct?
ALM
October 26th, 1999, 06:27 PM
Here's a function that does it. It outputs all the prime factors for a given positive number (which may or may not include the number itself):
void ShowPrimeFactors(unsigned nNumber)
{
cout << 1;
// Loop through every number between 2 and the number itself
for (unsigned iFactor = 2; iFactor <= nNumber; iFactor++)
{
// Check that it divides evenly (no remainder)
if ((nNumber % iFactor) != 0)
continue;
// Now check that it's a prime number
for (unsigned iPrime = 2; iPrime < iFactor; iPrime++)
{
// If a number divides evenly then it's not a prime
if ((iFactor % iPrime) == 0)
break;
}
// If we looped through all possible numbers, then it's a prime
if (iPrime == iFactor)
cout << ", " << iFactor;
}
cout << endl;
}
Cheers!
Alvaro