Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inbuilt __gcd(A,B) function in C++

Tags:

c++

recently I get to know about a special function in c++ : __gcd(A,B). this will return the greatest common divisor of A and B.

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

main()
{
cout<<__gcd(10,40); //op: 10
}

is there any special reason for starting function definition with 2 underscores?

It could be as simple as gcd(A,B) like other STL functions.

like image 680
GorvGoyl Avatar asked Jun 17 '15 17:06

GorvGoyl


People also ask

Is there a inbuilt GCD function in C?

C++ has the built-in function for calculating GCD. This function is present in header file. Syntax for C++14 : Library: 'algorithm' __gcd(m, n) Parameter : m, n Return Value : 0 if both m and n are zero, else gcd of m and n.

What is GCD in C program?

The HCF or GCD of two integers is the largest integer that can exactly divide both numbers (without a remainder). There are many ways to find the greatest common divisor in C programming.

What is the GCD of A and B?

A common divisor of a and b is any nonzero integer that divides both a and b. The largest natural number that divides both a and b is called the greatest common divisor of a and b. The greatest common divisor of a and b is denoted by gcd(a, b).


1 Answers

In C++17 there are standard library functions for GCD and LCM.

#include <iostream>
#include <numeric>

int main ()
{
    int a, b;
    std::cin >> a >> b;
    std::cout << std::gcd(a,b) << '\n';
    return (0);
}
like image 122
Kuji Avatar answered Oct 02 '22 10:10

Kuji