Solving notes (36) -- maximum number of common questions

Source: Internet
Author: User

 
Problem description: calculate the maximum common divisor of two positive integers.

 
Train of Thought: This is a very basic problem. The most common is the two methods, namely the moving and division method and the moving and Subtraction Method. The general formula is f (x, y) = f (y, X % Y), F (x, y) = f (y, x-y) (x> = Y> 0 ). It is not difficult to write an algorithm based on the general expression. I will not give it here. The algorithms in the beauty of programming are provided here to reduce the number of iterations.

 
For X and Y, if y = K * Y1, x = K * X1, f (x, y) = K * F (x1, Y1 ). In addition, if X = p * X1, assume that p is a prime number and Y % P! = 0, then f (x, y) = f (p * X1, y) = f (x1, Y ). Take P = 2.

 
Reference code:

// Function: calculate the maximum common approx. // function parameter: X and Y are two values // return value: 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 an odd {If (Y & 1) // y is an odd return gcd_solution1 (Y, x-y); else // y is an even return gcd_solution1 (X, y> 1);} else // X is an even number {If (Y & 1) // y is an odd number return gcd_solution1 (x> 1, y ); else // y is an even return gcd_solution1 (x> 1, Y> 1) <1 ;}}}

The following non-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;}elsey >>= 1;}else{if(y&1)x >>= 1;else{x >>= 1;y >>= 1;result <<= 1;}}}return result * x;}

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.