2つの数値のLCMを見つけるJavaプログラム
この記事では、Javaで2つの数値のLCMを計算する方法を理解します。 2つの数値の最小公倍数(LCM)は、両方の数値で均等に割り切れる最小の正の整数です。
以下は同じのデモンストレーションです-
入力
入力が-
であると仮定します24 and 18
出力
必要な出力は-
になりますThe LCM of the two numbers is 72
アルゴリズム
Step1- Start Step 2- Declare three integers: input_1, inpur_2 and sum Step 3- Prompt the user to enter two integer value/ Hardcode the integer Step 4- Read the values Step 5- Using a while loop from 1 to the bigger number among the two inputs, check if the 'i'value divides both the inputs without leaving behind reminder. Step 6- Display the 'i' value as LCM of the two numbers Step 7- Stop
例1
ここでは、プロンプトに基づいてユーザーが入力を入力しています。この例は、コーディンググラウンドツールでライブで試すことができます
。
import java.util.Scanner;
public class LCM {
public static void main(String[] args) {
int input_1 , input_2 , lcm;
Scanner scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.println("Enter the first number: ");
input_1 = scanner.nextInt();
System.out.println("Enter the second number: ");
input_2 = scanner.nextInt();
lcm = (input_1 > input_2) ? input_1 : input_2;
while(true) {
if( lcm % input_1 == 0 && lcm % input_2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", input_1, input_2, lcm);
break;
}
++lcm;
}
}
} 出力
A scanner object has been defined Enter the first number: 24 Enter the second number: 18 The LCM of 24 and 18 is 72.
例2
ここでは、整数は事前に定義されており、その値にアクセスしてコンソールに表示されます。
public class LCM {
public static void main(String[] args) {
int input_1 , input_2 , lcm;
input_1 = 24;
input_2 = 18;
System.out.println("The first number is " + input_1);
System.out.println("The second number is " + input_2);
lcm = (input_1 > input_2) ? input_1 : input_2;
while(true) {
if( lcm % input_1 == 0 && lcm % input_2 == 0 ) {
System.out.printf("\nThe LCM of %d and %d is %d.", input_1, input_2, lcm);
break;
}
++lcm;
}
}
} 出力
The first number is 24 The second number is 18 The LCM of 24 and 18 is 72.
-
正方形の領域を見つけるJavaプログラム
この記事では、正方形の面積を見つける方法を理解します。正方形の面積は、次の式を使用して計算されます- side*side i.e. s2 以下は同じのデモンストレーションです- 正方形の辺がsの場合、正方形の面積はs 2で与えられます。 − 入力 入力が-であると仮定します Length of the side : 4 出力 必要な出力は-になります Area of the square : 16 アルゴリズム Step 1 - START Step 2 - Declare 2 integer values namely my_side and my_area. S
-
2つの数の最大公約数のためのJavaプログラム
以下は、Javaの2つの数値の最大公約数の例です- 例 public class Demo{ static int find_gcd(int val_1, int val_2){ if (val_1 == 0) return val_2; return find_gcd(val_2%val_1,val_1); } static int common_divisors(int val_1,int