__gcd函数,求最大公约数

1447. 最简分数

_gcd()函数是内置于algorithm头文件中的函数,主要是用于求两个数的最大公约数

可用来判断是否为最简分数

class Solution {
public:
    // 哈希重复判断可约
    // vector<string> simplifiedFractions(int n) {
    //   vector<string> ans;
    //   unordered_set<double> sett;
    //   for(int i = 2; i<=n; i++){
    //     string temps;
    //     int fenmu = i;
    //     int fenzi = 1;
    //     while(fenzi<fenmu){
    //       double a = (double)fenzi/fenmu;
    //       cout<<a<<endl;
    //       if(sett.find(a) == sett.end()){
    //         sett.insert(a);
    //         temps+=to_string(fenzi);
    //         temps+="/";
    //         temps+=to_string(fenmu);
    //         cout<<temps<<endl;
    //         ans.push_back(temps);
    //         temps = "";
    //       }
    //       fenzi++;
    //     }
    //   }
    //   return ans;
    // }

    //__gcd函数,求最大公约数
    vector<string> simplifiedFractions(int n) {
      vector<string> ans;
      for(int i = 2; i<=n; i++){
        string temps;
        int fenmu = i;
        int fenzi = 1;
        while(fenzi<fenmu){
          if(__gcd(fenzi, fenmu) == 1){
            temps+=to_string(fenzi);
            temps+="/";
            temps+=to_string(fenmu);
            cout<<temps<<endl;
            ans.push_back(temps);
            temps = "";
          }
          fenzi++;
        }
      }
      return ans;
    }
};

  

posted @ 2022-02-10 11:40  千寻slimg  阅读(144)  评论(0编辑  收藏  举报