Home > Back-end >  The greatest common divisor and least common multiple
The greatest common divisor and least common multiple

Time:10-01

Java
The greatest common divisor and least common multiple
The specific requirements:
(1) write a class the Gcd: this class has a method public int f (int a, int b), the method returns the greatest common divisor of a and b;
(2) write a subclass of the Gcd Gcm: requirements subclasses override method f, and rewrite the method returns the least common multiple of a and b, requirements in rewriting method first calls the hidden method, return to a, b) the greatest common divisor of m, then the product (a * b)/m back,
(3) write a test class GcdGcmTest: create a superclass object, using the object finding the greatest common divisor of two integers; Then the object as a subclass of upload object, call f () method returns the smallest common multiple, run results similar to shown below:
Please enter the first integer: 27
Please enter the second integer: 45
27 and the greatest common divisor of 45 are as follows: 9
27 and least common multiple of 45:135


Public class the Gcd {
Public int f (int a, int b) {
If (a & lt; B) {//that a is the maximum
Int temp=a;
A=b;
B=temp.
}
While (b & gt; The greatest common divisor 0) {//o
If (a==b) {
return a;
}
The else {
Int temp=a % b;
A=b;
B=temp.
}
}
return a;
}

}


Public class Gcm extends the Gcd {
Public int f (int a, int b) {
Int j=super f (a, b);
Int result=(a * b)/m;
return result;
}
}




import java.util.Scanner;
Public class GcdGcmTest {
Public static void main (String [] args) {
The Gcd Gcd;
The GCD=new Gcm ();

The Gcd g=new Gcd ();

Scanner sc1=new Scanner (System. In);

System. The out. Print (" please enter the first integer: ");
Int a=sc1. NextInt ();
System. The out. Print (" please enter the second integer: ");
Int b=sc1. NextInt ();

Int m=g.f (a, b);
System. The out. Println (a + "and" a + b + "the greatest common divisor is:" + m);

Int n=GCD. F (a, b);
System. The out. Println (a + "and" a + b + "the least common multiple of is:" + n);


}
}
  • Related