-2
#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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Anonymous
  • 63
  • 2
  • 9

3 Answers3

2

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.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
0
int gcd(int a, int b){
    if (b == 0)
       return a;
    return gcd(b, a % b); 
}

As in my mac '__gcd()' is also not working and showing that "use of undeclared identifier' so I have to predefine this function.

cigien
  • 57,834
  • 11
  • 73
  • 112
Aayush Shah
  • 584
  • 1
  • 8
  • 17
0

As the other answer says, use the standard std::gcd instead of a non-standard __gcd, if possible.

That said, the error means that __gcd only works on unsigned integers. Change the types of your variables from int to unsigned int.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207