2016-11-05 28 views

回答

-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; 
} 
+0

我將如何轉換這個,以便它將接受一個int數組,其中a是? – user3832668

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 
+0

注意矢量的使用如何簡化代碼......計數和插入索引都是爲你照顧的。 –

+0

請注意,對於「show()」和方法「componentOf()」,向量和「for(auto iv:iVec)」的使用簡化了iVec內容的掃描。 –

+0

請注意遞歸代碼「LCM()」如何完全訪問類的任何數據屬性...例如,我不需要通過遞歸傳遞'array'ptr和長度,LCM()只需訪問實例iVec。我也不需要通過遞歸傳遞'tmp',但我認爲它看起來更熟悉它。 –