新手代码之循环语句的简单运用(求最小公倍数与与求最大公约数)

来源:互联网 发布:数据可视化管理 编辑:程序博客网 时间:2024/05/17 00:53
//求两个数的最小公倍数import java.util.Scanner;public class Study3 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter first integer: ");int n1 = input.nextInt();System.out.print("Enter second integer: ");int n2 = input.nextInt();int gcd = 1;int k = 2;if ((n1 < n2)){if (n2 % n1 == 0){System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + n2);}else System.out.println("The smallest common multiple for " + n1 + " and " + n2 + " is " + (n1 * n2));}if ((n1 > n2)){if (n1 % n2 == 0){System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + n1);}else System.out.println("The smallest common multiple for " + n1 + " and " + n2 + " is " + (n1 * n2));}}}
//求两个数的最大公约数import java.util.Scanner;public class Study4 {public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.print("Enter first integer: ");int n1 = input.nextInt();System.out.print("Enter second integer: ");int n2 = input.nextInt();int gcd = 1;int k = 2;while (k <= n1 && k <= n2){if (n1 % k == 0 && n2 % k == 0)gcd = k;k++;}System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd);}}


0 0