Java greatest common divisor and least common multiple

Source: Internet
Author: User
Tags greatest common divisor

Greatest common divisor has the following two ways:

method of dividing: Span style= "LINE-HEIGHT:24PX; Text-indent:28px "> aka Euclid algorithm (Euclidean algorithm) is an algorithm for finding the greatest common divisor of two positive integers.

toss and subtract: Span style= "LINE-HEIGHT:24PX; Text-indent:28px "", Nikoman the law greatest common divisor

Below are Java Code:

Public class Javabase
{
static public int gcd1_1 (int x, int y) // Non-recursive method of dividing
 {
int temp ;
  
do{
temp = x% y;
x = y;
y = temp;
}while (temp! = 0);
  
return x ;
 }
 
static public int gcd2_1 (int x, int y) // non-recursive subtraction
 {
int max, min;
int temp ;
max = (x > y)? x:y;
min = (x < y)? x:y;
  
while (max! = min)
  {
temp = max-min;
max = (temp > min)? temp:min;
min = (temp < min)? temp:min;   
  }
  
return Max ;
 }
 
static public int gcd1_2 (int x, int y) // recursive method of dividing
 {
return (y = = 0) x:gcd1_2 (y, x% y);
 }
 
static public int gcd2_2 (int x, int y) // recursive subtraction
 {
if (x = = y) return x;
return (x > Y) gcd2_2 (xy, y): gcd2_2 (x, y-x);
 }
 
public static void Main (String args[])
 {
int a = +, B =-;
int g = 0;
g = Gcd1_1 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd1_2 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd2_1 (A, b);
System.out.println ("greatest common divisor for:" + g);
g = Gcd2_2 (A, b);
System.out.println ("greatest common divisor for:" + g);
System.out.println ("least common multiple for:" + A * b/g);   // least common multiple
 }

Java greatest common divisor and least common multiple

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.