Use C++ to implement the following program about Prime Factorization of a Number. Do BOTH parts of the problem or you will lose points. Provide comments to explain each step.
a. Write a function that takes as a parameter a positive integer and returns a list (array) of the prime factors of the given integer. For example, if the parameter is 20, you should return 2 2 5.
b. Write a function that tests the above function by asking the user for input and displaying the output to screen. Your function should display the following menu:
1) Find the prime factorization of a number.
2) Quit.
PROGRAM:
# include <iostream>
# include <math.h>
//method for finding the prime factor
void primeFactorsOfANumber(int num)
{
//no prime factor exists for 0 and 1
if(num==0||num==1)
{
std::cout<<"\n No primefactor\n";
}
else{
//if the number is even,print 2 and divide the number by 2
while (num%2 == 0)
{
std::cout<< 2 <<" ";
num = num/2;
}
//initialize i=3 and i less than squareroot of the number
for (int i = 3; i <= sqrt(num); i = i+2)
{
//remainder of the number divided by i equal to 0
while (num%i == 0)
{
std::cout<< i<<" ";
num = num/i;
}
}
//number is greater than 2,print the number
if (num > 2)
{
std::cout<< num<<" ";
}
}
}
// Driver program
int main()
{
int num;
int choice;
do{
//menu
std::cout<<"\n1.Find The primeFactorial of a number\n";
std::cout<<"2. Quit\n";
std::cout<<"Enter your choice: ";
std::cin>>choice;
switch(choice)
{
case 1:
std::cout<<"\nEnter the NUmber : \n";
std::cin>>num;
//calling the function primeFactorsOfANumber
primeFactorsOfANumber(num);
break;
case 2:
//exit
return 0;
break;
}
}
while(1);
return 0;
}
OUTPUT:
1.Find The primeFactorial of a number
2. Quit
Enter your choice: 1
Enter the NUmber :
11
11
1.Find The primeFactorial of a number
2. Quit
Enter your choice: 1
Enter the NUmber :
24
2 2 2 3
1.Find The primeFactorial of a number
2. Quit
Enter your choice: 2
Program ended with exit code: 0
Get Answers For Free
Most questions answered within 1 hours.