Algorithm Learning-Euclidean algorithm (c + + implementation)

Source: Internet
Author: User

Euclidean algorithm

Euclidean algorithm is also called the greatest common divisor method, is the algorithm to find two integers.

Of course, can also seek least common multiple.

Algorithm implementation

In fact, the implementation principle of the algorithm is that there is a b an integer two, each time a number r = a % b , and then put b into a the position, put r to b the position, recursive call.

That's the gcd(a, b) { return gcd(b, a%b); } way it is.

The end condition is when a%b == 0 the time is stopped.

Greatest common divisor
////Main.cpp//Euclidean////Created by Alps on 15/3/28.//Copyright (c) 2015 Chen. All rights reserved.//#include <iostream>using namespace STD;intgcdintAintb) {if(A%b = =0) {returnb }returnGCD (b, a%b);}intMainintargcConst Char* argv[]) {intA = -, B = -;printf("%d\n", GCD (A, b));return 0;}

The above is the greatest common divisor of the request. In fact, through this also can seek least common multiple.

Least common multiple

Least common multiple, the product of which is a b divided by their two greatest common divisor, is their least common multiple. The code is as follows:

intintint b){    return (a * b)/gcd(a, b);}

That would be all right.

Algorithm Learning-Euclidean algorithm (c + + implementation)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.