document.querySelector('#gcdfinder').addEventListener('click', function() {
let firstNum = document.querySelector('#inPut10');
let secondNum = document.querySelector('#inPut10-1');
let fNumVal = Number(firstNum.value);
let sNumVal = Number(secondNum.value);
function twoNumGcd(a, b) {
if (b === 0) {
outPut.textContent = `You have NOT entered the second Number. The first number is: ${a}`;
}
twoNumGcd(b, a % b)
}
outPut.textContent = 'Your First Number is ' + fNumVal + ', the second is: ' + sNumVal + ', and the GCD of both numbers is: ' + twoNumGcd(fNumVal, sNumVal);
});
it works fine in finding the gcd but it displays the
You have NOT entered the second Number. The first number is: 2
for both conditions b === 0 or not.
the expected result b !== 0 should be
outPut.textContent = 'Your First Number is ’ + fNumVal + ', the second is: ’ + sNumVal + ', and the GCD of both numbers is: ’ + twoNumGcd(fNumVal, sNumVal);
I’ve really got stuck I tried many ways but …
this one displays both conditions but as you said the function returns undefined.
function twoNumGcd(a, b) {
if (b === 0) outPut.textContent = `You have NOT entered the second Number. The first number is: ${a}`;
else {
outPut.textContent = 'Your First Number is ' + fNumVal + ', the second is: ' + sNumVal + ', and the GCD of both numbers is: ' + twoNumGcd(b, a % b);
}
}
twoNumGcd(fNumVal, sNumVal);
Your twoNumGcd function must explicitly return a value or it will return undefined by default. You need two return statements in your twoNumGcd. One would be for returning a value for the base case and the other for returning the the result of the recursive call.
Also, if you want to warn the user about a missing second number, then you should check for that outside the twoNumGcd function.
document.querySelector('#gcdfinder').addEventListener('click', function() {
let firstNum = document.querySelector('#inPut10');
let secondNum = document.querySelector('#inPut10-1');
let fNumVal = Number(firstNum.value);
let sNumVal = Number(secondNum.value);
function twoNumGcd(a, b) {
if (b === 0) {
return a;
}
return twoNumGcd(b, a % b)
}
if (sNumVal === 0) {
outPut.textContent = `You have NOT entered the second Number. The first number is: ${fNumVal}`;
}
else {
outPut.textContent = 'Your First Number is ' + fNumVal + ', the second is: ' + sNumVal + ', and the GCD of both numbers is: ' + twoNumGcd(fNumVal, sNumVal);
}
});
Keep in mind the above does not deal with the case where the user enters a non-Number or for that matter a non-Integer.