Greatest common divisor (Java) for two numbers

Source: Internet
Author: User
Tags gcd greatest common divisor

Get two random numbers (less than 100) and put them in the array

 Public int [] Gettworandom () {      intnewint[2];       New Random ();        for (int i=0;i<t.length;i++)      {       = Rand.nextint (+);      }            return t;    }

1, the general algorithm, the continuous integer detection method is from M and N in the smaller number of the beginning of a traversal of integers, if there is a number that can be divisible by M and N, is greatest common divisor

//Continuous Integer Detection method     Public intGetDivisor1 (int[] arr) {        intT=0; intI1=0,i2=0;  for(inti=0;i<arr.length;i++) {I1=arr[0]; I2=arr[1]; }      if(i1>I2) {T=I2; }Else{T=I1; }       for(inti=t;i>1;i--){        if((i1%i==0) && (i2%i==0)){                    returni; }      }      return1; }

2. Euclidean algorithm

    Get an array of size 2 to determine the size of two numbers

 Public int getDivisor2 (int[] arr) {        int i1=40,i2=50;         /* for (int i=0;i<arr.length;i++) {         i1=arr[0];         I2=ARR[1];       */      int temp =0;         if (i1<i2) {            temp=i2;            I2=i1;            I1=temp;        }       return gcd (I1,I2);    }

(1), recursive method

 Public Static int gcd (int m,int// use recursive algorithm to implement            if(n==0) {             return m;        } Else {            return gcd (n,m%n);        }    }

(2), general circulation method

// using the while loop     Public Static int gcd1 (int m,int  n) {        int t = m%n;          while (t!=0) {            m=N;            n=t;            T=m%n;        }         return n;   }

Greatest common divisor (Java) for 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.