Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

#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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...