Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

c++ - Why __gcd() is throwing error in macOS mojave?

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
 
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> a(n);
   
    for(int i = 0; i < n; ++i)
        cin >> a[i];

    int ans = a[0];
    for(int i = 1; i < n; ++i)
       ans = __gcd(ans, a[i]);

    cout << ans << endl;

    return 0;
}

It is throwing the following error:

error: static_assert failed due to requirement '!is_signed::value'

note: in instantiation of function template specialization 'std::__1::__gcd' requested here ans = __gcd(ans, a[i]);

I am using command g++ -std=c++17 which worked for every program except this one.

This code is working without error on code.hackerearth.com online compiler which uses g++ 5.4.0

EDIT: Removed bits/stdc++.h header and included required headers only.

After removing also the same problem is happening.

The SAME code is running properly in online ide. Link of one such ide is ONLINE IDE

Using their c++ compiler and function __gcd(a, b) doesn't give any error but, when I change it to gcd(a, b) in the same ide, it does give error that this function definition is not found.

When I run the same code in my local machine, everything happens in just the opposite way. __gcd(a, b) doesn't work while gcd(a, b) works.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Don't use bit/C++.h, it's a private header.

Use proper C++ functions: https://en.cppreference.com/w/cpp/numeric/gcd

They support signed integers.

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main() {
int n;
cin >> n;
vector<int> a(n);

for(int i = 0; i < n; ++i)
    cin >> a[i];

int ans = a[0];
for(int i = 1; i < n; ++i)
   ans = gcd(ans, a[i]);

cout << ans << endl;

return 0;
}

works with clang++ -std=c++17.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...