Program JavaScript untuk Menemukan LCM

0
(0)

Kelipatan Umum Terkecil (LCM) dari dua bilangan bulat adalah bilangan bulat positif terkecil yang habis habis oleh kedua bilangan bulat.

Misalnya, KPK dari 6 dan 8 aku s 24.


Contoh 1: LCM Menggunakan While Loop dan Pernyataan If

// program to find the LCM of two integers

// take input
const num1 = prompt('Enter a first positive integer: ');
const num2 = prompt('Enter a second positive integer: ');

// higher number among number1 and number2 is stored in min
let min = (num1 > num2) ? num1 : num2;

// while loop
while (true) {
    if (min % num1 == 0 && min % num2 == 0) {
        console.log(`The LCM of ${num1} and ${num2} is ${min}`);
        break;
    }
    min++;
}

Keluaran

Enter a first positive integer: 6
Enter a second positive integer: 8
The LCM of 6 and 8 is 24

Dalam program di atas, pengguna diminta untuk memasukkan dua bilangan bulat positif.

Jumlah yang lebih besar di antara angka yang disediakan oleh pengguna disimpan di file min variabel. KPK dari dua angka tidak boleh kurang dari angka yang lebih besar.

Loop sementara digunakan dengan file if pernyataan. Di setiap iterasi,


KPK dari dua angka juga dapat ditemukan menggunakan rumus:

LCM = (num1*num2) / HCF

Untuk mempelajari tentang cara menemukan HCF, kunjungi program JavaScript untuk menemukan HCF.

Contoh 2: Perhitungan LCM Menggunakan HCF

// program to find the LCM of two integers

let hcf;
// take input
const number1 = prompt('Enter a first positive integer: ');
const number2 = prompt('Enter a second positive integer: ');

// looping from 1 to number1 and number2 to find HCF
for (let i = 1; i <= number1 && i <= number2; i++) {

    // check if is factor of both integers
    if( number1 % i == 0 && number2 % i == 0) {
        hcf = i;
    }
}

// find LCM
let lcm = (number1 * number2) / hcf;

// display the hcf
console.log(`HCF of ${number1} and ${number2} is ${lcm}.`);

Keluaran

Enter a first positive integer: 6
Enter a second positive integer: 8
The LCM of 6 and 8 is 24.

Dalam program di atas, pertama-tama nilai HCF dihitung. Kemudian KPK dihitung menggunakan rumus yang diberikan.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.