14 Euclid, extended Euclidean algorithm template

Source: Internet
Author: User
Tags gcd greatest common divisor

First, Euclidean algorithm: That is, the greatest common divisor method, used to find two integers, a, b

See: Greatest Common divisor templates

Second, extended Euclidean algorithm: for a non-total 0 nonnegative integer A,B,GCD (A, a, a, a, a, b) greatest common divisor, there must be an integer pair x, y, making gcd (A, b) =ax+by.

kb2.3 extended Euclidean algorithm (solution for AX+BY=GCD and inverse element)

#include <iostream>#include<stdio.h>using namespacestd;//returns D=GCD (A, b), and corresponding to x, y in equation Ax+by=dLong LongEXTEND_GCD (Long LongALong LongBLong Long&x,Long Long&y) {    if(a==0&&b==0)return-1;//no greatest common divisor    if(b==0) {x=1; y=0;returnA;} Long LongD=EXTEND_GCD (b,a%b,y,x); Y-=a/b*x; returnD;}//Seeking Inverse element//ax=1 (mod n)Long LongMod_reverse (Long LongALong LongN) {    Long Longx, y; Long LongD=EXTEND_GCD (a,n,x,y); if(d==1)return(x%n+n)%N; Else return-1;}intMain () {Long LongA,b,x,y; scanf ("%lld%lld",&a,&b); Long LongD=EXTEND_GCD (a,b,x,y); printf ("%lld x=%lld y=%lld\n", D,x,y); return 0;}
View Code

14 Euclid, extended Euclidean algorithm template

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.