【问题标题】:inbuilt std::__gcd() function for c++ is not working on Mac OS Xcodec++ 的内置 std::__gcd() 函数在 Mac OS Xcode 上不起作用
【发布时间】:2020-04-09 19:01:44
【问题描述】:

内置的 __gcd() 函数在 Xcode macOS 上不起作用。 我在 Xcode (macOS Catalina) 上运行了以下代码,它显示错误 "使用未声明的标识符 '__gcd'"。

#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    cout << "gcd(6, 20) = " << __gcd(6, 20) << endl;
    return 0;

}

请帮帮我

【问题讨论】:

  • __gcd 中的双前导下划线表示它是实现定义的符号,并且可能是私有的。

标签: c++ xcode macos macos-catalina


【解决方案1】:

如果你用-std=c++17编译,你可以使用&lt;numeric&gt;中的那个

#include <numeric>

int main()
{
    std::cout << "gcd(6, 20) = " << std::gcd(6, 20) << std::endl;
    return 0;
}

【讨论】:

  • __gcd 是一个内部实现细节,因此 __ 前缀,你不应该在你的代码中依赖它。
  • @Adarshyadav 自 c++17 起在 中可用
【解决方案2】:

感谢提问,
在头文件下面使用以下函数,因为 gcd 在 mac m1 中不起作用:

int __gcd(int a, int b) { 
    if (b == 0) { 
        return a; 
    } 
    return gcd(b, a % b); 
}

那么你就可以轻松高效地使用__gcd(a, b)函数了。

【讨论】:

  • 请不要发布重复的答案。其他人已经发布了相同的答案。
【解决方案3】:

std::gcd() 在 c++17 中可用

否则,

两个非负整数的 GCD 很容易计算:

int gcd(int a, int b){ int c = a % b; while(c != 0) { a = b; b = c; c = a % b; } return b;}

参见。 https://www.gamedev.net/forums/topic/358629-built-in-c-command-for-gcd/3354131/

【讨论】:

    【解决方案4】:

    这里的一些答案包含用于计算 gcd 的基于欧几里德的代码。例如:

    int gcd(int a, int b) { if(b == 0){return a;} return gcd(b, a % b); }
    

    您必须注意传递给此函数的实际参数的顺序。代码基于a&gt;0b&gt;0a&gt;=b 的假设。

    可以修改代码以消除这些假设。

    int gcd(int a,int b)
    {
        if(a<0 or b<0)
            return -1;
        
        if(a>b)
            return gcd(b,a);
        
        if(a==0)
            return b;
        
        //Due to Euclidean algorithm
        return gcd(a,b%a); 
    }
    

    如果您坚持使用第一个版本,则必须注意根据上述假设发送参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      相关资源
      最近更新 更多