Saturday, May 29, 2021

Javascript Practice 68: JS Hero - do...while loop

 
Question: 

Write a function lcm that takes two natural numbers and calculates their least common multiple (lcm). The lcm of two natural numbers a und b is the smallest natural number that is divisible by a and b.

Example: lcm(4, 6) should return 12.




Answer: 

function lcm(a, b) {

  let theLCM = 0;
  let remainderA;
  let remainderB;

  do {

    theLCM++;
    remainderA = theLCM % a;
    remainderB = theLCM % b;

  } while (remainderA !== 0 || remainderB !== 0)

  return theLCM;
}



> we declare a function lcm
> it has 2 parameters: 'a' and 'b'
> we declare a variable 'theLCM' & initialize it with a value of 0; 
> we declare 2 empty variables: 'remainderA' & 'remainderB' 
> we open a do while loop 
> do/while loop is a variant of the while loop
> this loop will execute the code block once, before checking if the condition is true
> then it will repeat the loop as long as the condition is true
> to understand this function, we shall illustrate this function with an example of lcm(2,4)
> when the function lcm (2,4) is called, the loop will execute the code block (the 'do' part)     
>>> it will first add 1 to theLCM variable (0 +1)
>>> it will then store the remainder value of ' theLCM%a ' in remainderA variable
>>> like this: 1 % 2 = 1 (it is actually 0.5 and there has to be a reason for it which I do not know as of now)
>>> it will then store the remainder value of ' theLCM%b ' in remainderB variable
>>> like this: 1 % 4 = 1 (it is actually 0.25 and there has to be a reason for it which I do not know as of now)
>>> it will now check if the condition is true (the 'while' part)
>>> our condition is basically checking if remainderA or remainderB is 'NOT' equal to 0
>>> since both remainderA & remainderB are 1 and 1 is not equal to 0; our loop is repeated
>>> it keeps repeating till the time our remainderA is equal to 0
>>> then it will check if remainderB is not equal to 0
>>> if remainderB is also equal to 0, then our loop will stop 
>>> in our case the loop will stop at 4 as ' 4 % 2 = 0 ' & ' 4 % 4 = 0 '
>>> and once the loop stops, the function will execute the statement after the loop
>>> our last statement is the return statement and we shall return the variable theLCM

No comments:

Post a Comment