2016-03-04 57 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; 
}