Greatest common divisor, least common multiple algorithm

Source: Internet
Author: User
Tags gcd greatest common divisor

#include <iostream>using namespace std;//Example://2 | 8 6//----------//4 3//so: gcd=2,lcm=2*4*3=24//for Greatest common divisor: the Division method//1. A÷b, the R is the resulting remainder (0≤R&LT;B)//If R = 0, the algorithm ends; b is the answer. 2. Swap: Place A←b,b←r and return the first step int gcd1 (int m, int n) {int r;while (n) {r = m% N;m = N;n = r;}; return m;} int gcd2 (int m, int n) {if (n) return GCD1 (n, m%n); Elsereturn m;} Least common multiple: Formula method//Because the product of two numbers equals the product of greatest common divisor and least common multiple of these two numbers. That is (A, b) x[a,b]=axb. Therefore, to find the least common multiple of two numbers, we can first find out their greatest common divisor, and then use the above formula to find their least common multiple. int LCM (int m, int n) {return (m*n)/GCD1 (m, n);} int main () {int m, n;cout<< "input numbers:" <<endl;while (cin>>m) {cin>>n;if (m<=0 | | n<=0) {cerr<< "Error input!!!" <<endl;cout<< "Input numbers:" <<endl;continue;} cout<< "gcd (" <<m<< "," <<n<< ") =" &LT;&LT;GCD1 (m, N) <<endl;cout<< "LCM (" <<m<< "," <<n<< ") =" &LT;&LT;LCM (m, n) <<endl;cout<< "input-numbers:" << Endl;} return 0;}

Greatest common divisor, least common multiple algorithm

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.