2009-03-14
展开全部
import java.math.BigInteger;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
/* Gets two numbers from keyboard */
Scanner scanner = new Scanner(System.in);
BigInteger firstNumber = getNumber("Enter the first number: ", scanner);
BigInteger secondNumber = getNumber("Enter the second number: ", scanner);
/* Calculates the greatest common divisor */
BigInteger gcd = firstNumber.gcd(secondNumber);
/* Calculates the least common multiple */
BigInteger lcm = firstNumber.multiply(secondNumber).divide(gcd);
/* Prints out the results */
System.out.println("Greatest Common Divison: " + gcd);
System.out.println("Least Common Multiple: " + lcm);
}
/**
* Gets a number from keyboard
*/
static BigInteger getNumber(String message, Scanner scanner) {
while (true) {
try {
System.out.println(message); // displays the message
String number = scanner.next(); // gets a token
BigInteger integer = new BigInteger(number); // Constructs an integer object
if (integer.compareTo(BigInteger.ZERO) < 0) {
throw new NumberFormatException(); // number less than 0 is not allowed
}
return integer;
} catch (NumberFormatException e) {
System.out.println("Invalid number!"); // if not a number, repeat
}
}
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
/* Gets two numbers from keyboard */
Scanner scanner = new Scanner(System.in);
BigInteger firstNumber = getNumber("Enter the first number: ", scanner);
BigInteger secondNumber = getNumber("Enter the second number: ", scanner);
/* Calculates the greatest common divisor */
BigInteger gcd = firstNumber.gcd(secondNumber);
/* Calculates the least common multiple */
BigInteger lcm = firstNumber.multiply(secondNumber).divide(gcd);
/* Prints out the results */
System.out.println("Greatest Common Divison: " + gcd);
System.out.println("Least Common Multiple: " + lcm);
}
/**
* Gets a number from keyboard
*/
static BigInteger getNumber(String message, Scanner scanner) {
while (true) {
try {
System.out.println(message); // displays the message
String number = scanner.next(); // gets a token
BigInteger integer = new BigInteger(number); // Constructs an integer object
if (integer.compareTo(BigInteger.ZERO) < 0) {
throw new NumberFormatException(); // number less than 0 is not allowed
}
return integer;
} catch (NumberFormatException e) {
System.out.println("Invalid number!"); // if not a number, repeat
}
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询