I need some help with the prime_factor fxn. I think I'm just missing something easy that I'm not seeing right now. Anyways, it's supposed to output the prime factors of an input number.
When I input 12, it outputs the desired results; however, if I enter in another nonprime number, it doesn't output the desired results. For example, if I input 6, it only says that 2 is a factor, but does not say 3 is a factor.
Ex. Output:
Enter an integer < 1000 -> 12
The prime factorization of the number 12 is:
2 is a factor
2 is a factor
3 is a factor
______________________
Enter an integer < 1000 -> 6
The prime factorization of the number 6 is:
2 is a factor
// It doesn't output that 3 is also a factor for the number 6.
Here's an example main to go with the program, followed by the function I need help with:
Code:#include <iostream> #include <string> #include <cmath> using namespace std; const string SPACE_STR = " "; void prime_factor(int number); bool is_prime(int number); int main() { int number; cout << "Enter a number < 1000 -> "; cin >> number; prime_factor(number); return 0; } // Function I need help with. void prime_factor(int number) { bool isPrime = is_prime(number); int prime = number; int i = 2, j; double squareRoot = sqrt(static_cast<double>(number)); int count = 0; cout << "The prime factorization of the number " << number << " is:" << endl; if(isPrime) cout << SPACE_STR << number << " is a prime number." << endl; else { while((prime > 0) && (i <= squareRoot)) { if((prime % i) == 0) { count++; for(j = 0; j < count; j++) cout << SPACE_STR; cout << i << " is a factor" << endl; prime /= i; } else i++; } } } bool is_prime(int number) { int i; for(i = 2; i < number; i++) { if((number % i) == 0) return false; } return true; }



LinkBack URL
About LinkBacks


