Greatest common divisor and least common multiple of the algorithm

Recently I began to brush some simple C language problem. Seeking to achieve a greatest common divisor and least common multiple of the subject, there is the impression that he has done, but still found unskilled, all I decided to write down ideas, for later review using.

 

First of all I think of a way to solve the direct violence, one by one try, because the greatest demand, all from large to small scale, is the first to meet the conditions of the greatest common divisor, as follows

 1 #include<iostream>
 2 #include<stdio.h>
 3 using namespace std;
 4 int main()
 5 {
 6     int m,n;
 7     int common=1000;
 8     cin>>m;
 9     cin>>n;
10     while(1)
11 {
12     
13     if(m%common==0&&n%common==0)
14     {
15         cout<<common;
16         break;
17     }
18     
19     else{
20         common--;
21     }
22     
23 }    return 0;
24 }

Of course, this is actually a better understanding of the most direct way, but when the numbers growing, its efficiency is clearly not high.

 

Here there is a second method "Euclidean":

  This method is also well understood, we take the first two numbers, a max a min, representing two numbers in which the larger and smaller.

  The first step: the results obtained with a max% min, we take a variable temp to store it. Thus temp = max% min;

  Step Two: assign the value min max, min is assigned a value of temp, continuing the above process until temp = 0; that is, on a greatest common divisor of the temp (i.e., the round max)

 1 #include <iostream> 
 2 using namespace std;
 3 int main()
 4 {
 5     int temp=1,max,min;
 6     cin>>max;
 7     cin>>min;
 8     while(temp)
 9     {
10         temp=max%min;
11         max=min;
12         min=temp;
13     }
14     cout<<max;
15     return 0;
16 }

After obtaining the greatest common divisor of the least common multiple becomes very short answer, which is equal to (max * min) / temp; point and the least common multiple calculated greatest common divisor.

Guess you like

Origin www.cnblogs.com/Truedragon/p/12213634.html