Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program that use\'s a recursive function that writes out prime facto

ID: 668621 • Letter: W

Question

Write a C++ program that use's a recursive function that writes out prime factorization of an input integer and comment to explain how the function works.

Recursion is a programming technique in which a function calls itself. It is another way of implementing repetitive computations, which we have previously associated with loops. When called to solve a problem, a recursive function passes a smaller version (or versions) of the problem to another instance (or other instances) of itself, then uses the results returned by the recursive call or calls to build the solution to the original problem.

.

PRIME FACTORIZATION

The smallest nontrivial factor of a positive integer is necessarily prime. (Can you prove this by contradiction?) Write a recursive function that takes advantage of this fact to write the prime factors of an integer greater than 1 to the terminal inascending order.

A run of a program that exercises this function might look like this:

Hint: Begin by writing a function that returns the smallest factor of its positive integer argument. The recursive function will call this one.

Question: How would you modify the function to print the prime factors in descending order?

Explanation / Answer

void printPrimeFactors(int num, int div = 2)
{
if (num % div == 0) {
std::cout << div << " ";
printPrimeFactors(num / div, div);
} else if (div <= num) {
printPrimeFactors(num, div + 1);
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote