2016-03-04 58 views
-2

我的代碼如下。這是C++代碼。 此代碼在兩個數字中進行通用劃分。 例如,如果輸入是18,24,則輸出是2,2,2,3,3。 但我只想輸出2和3。 我無法修復它。我怎樣才能解決這個問題?感謝您的幫助...爲了避免在C++中重複數組中的數字

#include<iostream> 
using namespace std; 
class Ratio { 
    public: 
     Ratio(int numerator, int denumerator) { 
      num=numerator; 
      den=denumerator; 
     } 

     void commondivisor() { 
      int arr[20]; 
      int arr2[20]; 
      int c=0; 
      int c2=0; 
      for (int q = 2; num != 1; q ++) 
      { 
       if (num % q == 0) 
       { 
        num /= q; 
        arr[c]=q; 
        q --; 
        c++; 
       } 
      } 
      cout << endl; 

      for (int w = 2; den != 1; w ++) 
      { 
       if (den % w == 0) 
       { 
        den /= w; 
        arr2[c2]=w; 
        w --; 
        c2++; 
       } 
      } 

      for (int i=0; i<c; i++) { 
       for (int j=0; j<c2; j++) { 
        if (arr[i]==arr2[j]) 
         cout<<arr2[j]; 
       } 
      } 
     } 


    private: 
     int num; 
     int den; 
}; 

int main() { 

    int a; 
    int b; 
    cin >> a; 
    cin >> b; 
    Ratio nesne(a,b); 
    nesne.commondivisor(); 
    return 0; 
} 
+0

您是否在插入前嘗試找到它? http://en.cppreference.com/w/cpp/algorithm/find – willll

+0

是的,但沒有 – frkn6161

回答

0

您的尋找因子的算法並不真正奏效?例如,對於數字18和24,分別應該是{1,2,3,6,9,18}和{1,2,3,4,6,8,12,24},包括1和數字本身。您分別獲得{2,3,3}和{2,2,2,3}。

std::vector<int> factors(int num) { 
    std::vector<int> fac_vec; 
    for (int i = 1; i <= num; i++) 
     if (num % i == 0) 
      fac_vec.push_back(i); 
    return fac_vec; 
} 

這個工程,認爲它並不是有效的。要查找常見元素,可以使用嵌套循環進行迭代。同樣,效率不高,特別是因爲矢量/數組被排序。見下面的例子。

std::vector<int> find_common(std::vector<int>& l, std::vector<int>& r) { 
    std::vector<int> common_vec; 
    for (auto il : l) 
     for (auto ir : r) 
      if (il == ir) 
       common_vec.push_back(ir); 
    return common_vec; 
}