This lab is due one week from the day it is assigned. A lab submitted beyond the
ID: 3828753 • Letter: T
Question
This lab is due one week from the day it is assigned. A lab submitted beyond the due date will not be accept except for a documentable and valid excuse. Upon completion you must upload .m file (or .cpp if done in C++) to Blackboard using the following convention Username Lab #.m by 3:59 PM of the due date. You must also show your completed lab to your instructor during the lab to receive credit. Blackboard submissions that have not been shown to your instructor will not be accepted. In this lab, we will use MATLAB/C++ to implement the Greatest Common Divisor (GCD) and the Least Common Multiple (LCM). Please carefully read and follow the descriptions of each problem Prime Factorization of a Number Write a function that takes as a parameter a positive integer and returns a list (array or vector in MATLAB/C++) of the prime factors of the given integer. For example, if the parameter is 20, you should return 2 2 5. GCD Write a function that takes as a parameter a list array or vector in MATLAB/C++) of 2 or more positive integers. Return the GCD of all elements in the list. For example, the GCD of 10 20 30 is 10 Write a function that takes as a parameter a list (array or vector in MATLAB/C++) of 2 or more positive integers. Return the LCM of all elements in the list. For example, the LCM of 10 20 30 is 60. Write a function that tests the above functions by asking the user for input and displaying the output to screen. Your function should display the following menu: Find the prime factorization of a number Find the GCD of a series of numbers Find the LCM of a series of numbers Quit Your function should continuously display the menu until the quit option is selected. Have fun and ensure your functions are well commented.Explanation / Answer
code:
#include<cstdio>
#include<string.h>
#include<cstdlib>
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
vector<int> primeFactors(int n)
{
vector<int> result;
while (n%2 == 0)
{
result.push_back(2);
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
result.push_back(i);
n = n/i;
}
}
if (n > 2)
result.push_back(n);
return result;
}
int gcd(int n1,int n2)
{
// /cout<<"in gcd";
while(n1 != n2)
{
if(n1 > n2)
n1 -= n2;
else
n2 -= n1;
}
return n1;
}
int lcm(int a,int b)
{
int m,n;
m=a;
n=b;
while(m!=n)
{
if(m < n)
{
m=m+a;
}
else
{
n=n+b;
}
}
return m;
}
int main ( int argc, char *argv[] )
{
vector<int> res=primeFactors(10);
for(int i=0;i<res.size();i++)
cout<<res[i]<<" ";
cout<<endl;
cout<<gcd(5,15)<<endl;
cout<<lcm(5,15)<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.