Use C++ to implement the following program about Prime Factorization of a Number
ID: 3858027 • Letter: U
Question
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.
Explanation / Answer
C++ Code:
#include<bits/stdc++.h>
using namespace std;
void Prime_Factors(int n) //prime factor function which gives the prime factors
{ int i;
// Print the number of 2s that divide n
while (n%2 == 0)
{
cout<<2<<" ";
n = n/2;
}
// n must be odd at this point. So we can skip
// one element (Note i = i +2)
for (i = 3; i <= sqrt(n); i = i+2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
cout<<i<<" ";
n = n/i;
}
}
// This condition is to handle the case when n
// is a prime number greater than 2
if (n > 2)
cout<<n<<" ";
}
int main() //main function which displays the menu
{
int n,p;
do{ cout<<endl<<"1.Find the prime factorization of a number."<<endl;
cout<<"2.Exit"<<endl;
cout<<"Enter an option: ";
cin>>p;
if(p==1)
{
cout<<"Enter the number for which we have to fing prime factors: ";
cin>>n;
cout<<"The prime factors are: ";
Prime_Factors(n);
}
}while(p!=2);
return 0;
}
Output:
1.Find the prime factorization of a number.
2.Exit
Enter an option: 1
Enter the number for which we have to fing prime factors: 120
The prime factors are: 2 2 2 3 5
1.Find the prime factorization of a number.
2.Exit
Enter an option: 1
Enter the number for which we have to fing prime factors: 100
The prime factors are: 2 2 5 5
1.Find the prime factorization of a number.
2.Exit
Enter an option: 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.