The method of GCD and LCM of two numbers in C language _c language

Source: Internet
Author: User
Tags gcd

GCD of two positive integers

Train of thought: This is a very basic problem, the most common is two methods, Euclidean method and subtraction. The formula is f (x, y) = f (y, x%y), f (x, y) = f (y, XY) (x >=y > 0). It is not difficult to write an algorithm according to the formula, which is not given here. Here is the "beauty of programming" algorithm, mainly to reduce the number of iterations.
For x and y, if y = k * y1, x= k * X1, then f (x, y) = k * F (x1, y1). In addition, if x = p * x1, assuming P is prime and y% p!= 0, then f (x, y) = f (p * x1, y) = f (x1, y). Take P = 2.

Reference code:

function function: Find GCD 
//function parameter: X,y is two number 
//return value:  gcd 
int gcd_solution1 (int x, int y) 
{ 
  if (y = = 0) 
    return x; 
  else if (x < y) return 
    gcd_solution1 (y, x); 
  else 
  { 
    if (x&1)//x is odd 
    { 
      if (y&1)//y is odd return 
        gcd_solution1 (y, xy); 
      Else  //y is an even return 
        gcd_solution1 (x, y>>1) 
    ; 
    Else//x is an even 
    { 
      if (y&1)//y is an odd return 
        Gcd_solution1 (x>>1, y); 
      Else  //y is an even return 
        Gcd_solution1 (x>>1, y>>1) << 1 
    } 
  } 
} 

Ask LCM:
The most commonly used is the Euclidean method, which has two integers a and B:
①a%b to the remainder C
② if c=0, then B is two number of GCD
③ if c≠0, then a=b,b=c, then go back to execute ①

The following are not recursive versions:

int gcd_solution2 (int x, int y) 
{ 
  int result = 1; 
  while (y) 
  { 
    int t = x; 
    if (x&1) 
    { 
      if (y&1) 
      { 
        x = y; 
        y = t% y; 
      } 
      else 
        y >>= 1; 
    } 
    else 
    { 
      if (y&1) 
        x >>= 1; 
      else 
      { 
        x >>= 1; 
        Y >>= 1; 
        Result <<= 1; 
  }} return result * x; 
} 

Related Article

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.