The beauty of programming-2.7-the maximum common Number Problem

Source: Internet
Author: User

1. Brief Introduction

Write a program to calculate the maximum common number of two positive integers. If the two positive integers are large, is there any simple method?

2. Ideas

The summary in this book is complete.

Division of the moving phase. If f (x, y) is used to represent the most common factor between x and y, if x = y * k + z, z> 0, then f (x, y) = f (y, z). If x = y * k + z, z = 0, f (x, y) = y, that is, x can be divisible by y. For example, f (6, 4) = f (4, 2) = 2, f (24, 18) = f (18, 6) = 6.

Improvement Method: when a positive integer is large, Division of large numbers consumes time. Division of large numbers is avoided here.
Adjust x and y each time to ensure x> = y, and then discuss the situation as follows:
When y = 0, f (x, y) = x. That is, x is the factor that can be divisible in the previous step.
If x % 2 = 0 and y % 2 = 0, f (x, y) = 2 * f (x/2, y/2) indicates that all values are even numbers.
When x % 2 = 0 and y % 2! If it is 0, f (x, y) = f (x/2, y) indicates an odd number and an even number.
When x % 2! If it is 0 and y % 2 = 0, f (x, y) = f (x, y/2) indicates an odd number and an even number.
When x % 2! = 0 and y % 2! = 0, f (x, y) = f (x-y, y), that is, two odd numbers. Use subtraction instead of division.
In fact, we use subtraction between large numbers and division between large numbers and non-large numbers to avoid division between large numbers.

3. Code

Omitted.

4. Reference

The beauty of programming, section 2.7, the maximum number of common appointments.

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.