This is a C++ problem: It is a well-known mathematical fact that every integer g
ID: 3677540 • Letter: T
Question
This is a C++ problem:
It is a well-known mathematical fact that every integer greater than or equal to 2 has a unique factorization into prime numbers. For example:
40 = 2 * 2 * 2 * 5
58 = 2 * 29
9 = 3 * 3
30 = 2 * 3 * 5
100 = 2 * 2 * 5 * 5
Write a recursive function:
void printPrimeFactorization(int n, bool firstcall);
that prints out the prime factorization of the number n. (You will need to figure out for yourself the purpose of the boolean argument firstcall.)
For example, if n == 40, it should print out:
The prime factorization of 40 is 2 * 2 * 2 * 5.
also, our professor ask us to write a loop to find the smallest integer greater than or equal to 2 that divides n,
then print out this integer and call the function recursively on n/k
Explanation / Answer
#include <iostream>
using namespace std;
void printPrimeFactorization(int n,bool firstCall)
{
if(n<2)
{
return;
}
else
{
int i=0;
for(i=2;i<=n;i++)
{
if(n%i==0)
{
if((n/i)<2)
cout << i;
else
cout << i << "*";
break;
}
}
return printPrimeFactorization(n/i,false);
}
}
int main() {
// your code goes here
cout << "40 = ";
printPrimeFactorization(40,true);
cout << endl;
cout << "100 = ";
printPrimeFactorization(100,true);
cout << endl;
cout << "58 = ";
printPrimeFactorization(58,true);
cout << endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.