请有人帮助我使用递归函数来查找整数数组的LCM。
函数调用将是:int LCM(int * arr, int length){}
请有人帮助我。
答案 0 :(得分:0)
您已将此标记为C ++。这是一种可能的C ++方法,使用std :: vector。
class T435_t
{
private:
std::vector<int> iVec;
void show(std::string label)
{
std::cout << label << std::endl;
for (auto iv : iVec)
std::cout << " iVec " << std::setw(6) << iv << std::endl;
std::cout << std::endl;
}
public:
T435_t() // : std::vector<int> iVec - default ctor ok
{
}
~T435_t() { }
int exec()
{
// test data
iVec.push_back(5);
iVec.push_back(10);
iVec.push_back(15);
iVec.push_back(20);
iVec.push_back(25);
show("\n ---- ---");
int retVal = LCM(1); // start tmp at 1
std::cout << " LCM " << std::setw(6) << retVal << std::endl;
return(0);
}
private:
inline bool componentOf (int tmp)
{
size_t count = 0;
for (auto iv : iVec)
{
if (0 == (tmp % iv))
++count; // how many elements of vec are component
}
return (count == iVec.size()); // when all are
}
// recursion
int LCM(int tmp)
{
if (componentOf(tmp)) // recursion termination clause
return (tmp);
return (LCM (++tmp)); // probably tail recursion with -O3
}
};
int main(int argc, char* argv[] )
{
std::cout << "argc: " << argc << std::endl;
for (int i=0; i<argc; i+=1) std::cout << argv[i] << " ";
std::cout << std::endl;
setlocale(LC_ALL, "");
std::ios::sync_with_stdio(false);
T435_t t435; // C++ uses classes!
int retVal = t435.exec();
std::cout << "\nFINI " << std::endl;
return(retVal);
}
输出:
---- ---
iVec 5
iVec 10
iVec 15
iVec 20
iVec 25
LCM 300
输出5和6编码到iVec
---- ---
iVec 5
iVec 6
LCM 30
答案 1 :(得分:-1)
int lcm(int a,int b){
static int temp = 1;
if(temp % b == 0 && temp % a == 0)
return temp;
temp++;
lcm(a,b);
return temp;
}