Java two number of GCD LCM __java

Source: Internet
Author: User
Tags gcd

Euclidean method.

When the two numbers are large, it is more convenient to use the Euclidean method. The method is:

In addition to the large number of decimals, if divisible, then the decimal is the GCD. Otherwise, use the remainder to remove the divisor, and then use the remainder of the new division to remove the remainder. And so on, until a division is divisible, then the number of divisor is the GCD.

For example: When you ask for a GCD of 4453 and 5767, you can divide the following.

5767÷4453=1 Yu 1314

4453÷1314=3 Yu 511

1314÷511=2 Yu 292

511÷292=1 Yu 219

292÷219=1 Yu 73

219÷73=3

It was then learned that 5767 and 4453 of the GCD were 73.

The Euclidean method is widely used, which is much better than short division, which can guarantee the GCD of any two numbers.


Class Ex1
{
  int gys1 (int m, int n)   //Loop implementation
  {
    int k,y;
    if (m<n)
    {
      k=m;
      m=n;
      n=k;
   }
    while (m%n!=0)
    {
     y=m%n;
     m=n;
     n=y; 
   }
    return n;
 }

int gys2 (int m,int n)//recursive implementation
{
int k,y;
if (m<n)
{
K=m;
M=n;
N=k;
}
y=m%n;
if (y==0)
{
return n;
}
Else
{
M=n;
N=y;
Return Gys2 (M,n);
}
}

public static void Main (string[] args)
{
Ex1 e1=new Ex1 ();
System.out.println (E1.gys1 (256,128));
Ex1 e2=new Ex1 ();
System.out.println (E1.gys2 (256,128));
}
}

===================================================================

Import java.util.*; 
Class Num 
{public 
static void Main (String args[]) 
{int m,n; 
Scanner s=new Scanner (system.in); 
System.out.println ("Please enter the number you want to count:"); 
M=s.nextint (); 
N=s.nextint (); 
int total, R; 
Total=m*n; 
Do 
{ 
if (m<n) 
{ 
int t=m; 
M=n; 
n=t; 
} 

r=m%n; 
M=n; 
n=r; 
} while (r!=0); 
SYSTEM.OUT.PRINTLN ("Max Common divisor is:" +m); 
System.out.println ("LCM is:" +total/m); 
} 

Related Article

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.