A method for finding the greatest common divisor of two numbers

Source: Internet
Author: User
Tags greatest common divisor

For two integers x, y, greatest common divisor (language: c,c++)

Principle: The division of the greatest common divisor: is constantly using the divisor to remove the remainder, until the remainder is 0, the resulting divisor is the two number of greatest common divisor

1. Recursive method:

    1. int gcd (int x,int y)
    2. {
    3. int result;
    4. if (y==0)
    5. Result=x;
    6. Else
    7. RESULT=GCD (y,x%y);
    8. return result;
    9. }

2. Non-recursive method (Euclidean method)

  1. int gcd (int x,int y)
  2. {//Greatest common divisor: the remainder is continuously removed with the divisor until the remainder is 0
  3. int tem ;
  4. While (x%y!=0)
  5. {
  6. tem=x%y;
  7. X=y;
  8. Y=tem;
  9. }
  10. return y;
  11. }

A method for finding the greatest common divisor of two numbers

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.