Greatest common divisor of two numbers (Euclid algorithm)

Source: Internet
Author: User
Tags gcd greatest common divisor

Greatest common divisor of two numbers p and q (Greatest common divisor,gcd), using properties

If p > Q, p and q are greatest common divisor = q and (p% q) of greatest common divisor.

Proof: See http://blog.csdn.net/niushuai666/article/details/7278027

 Public classeuclid{//recursive inplementation     Public Static intgcdintPintq) {        if(q = 0)returnp; Else{stdout.println (q+ "" + p%q); returnGCD (q, p%q); }    }    //non-recursive Implementation     Public Static intGCD2 (intPintq) {     while(Q! = 0){        inttemp =Q; Q= p%Q; P=temp; }    returnp; }     Public Static voidMain (string[] args) {intp = integer.parseint (args[0]); intQ = Integer.parseint (args[1]); intD =gcd (P, q); intD2 =GCD2 (P,Q); Stdout.println ("GCD (" + p + "," + q + ") =" +d); Stdout.println ("GCD (" + p + "," + q + ") =" +D2); }}

Run results

Greatest common divisor of two numbers (Euclid algorithm)

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.