Find LCM (Least Common Multplies) from array values in Javascript
by MariGanesh[ Edit ] 2014-06-11 11:42:11
Find LCM (Least Common Multplies) from array values
Use this code to find LCM of the array values in javascript . just give the set of numbers with separated comma in textbox.
<html>
<head>
<title>Find LCM (Least Common Multplies) from array values in Javascript</title>
<script type='text/javascript'>
function checnum(as)
{
var a = as.value;
as.value = a.replace(/[^-,//d]/g,'');
}
function gcf(a, b) {
return ( b == 0 ) ? (a) : ( gcf(b, a % b) );
}
function lcm(a, b) {
return ( a / gcf(a,b) ) * b;
}
function lcm_nums(ar) {
if (ar.length > 1) {
ar.push( lcm( ar.shift() , ar.shift() ) );
return lcm_nums( ar );
} else {
return ar[0];
}
}
function resultt()
{
var lcmval=document.getElementById('lcm').value;
var ar=lcmval.split(',');
var res=lcm_nums(ar);
document.getElementById('res').value=res;
}
</script>
</head>
<body>
<label><b>Numbers</b>:</label>
<input name='' type='text' id='lcm' > (separated by commas) <img src="http://www.hiox.org/smilies/icon_e_sad.gif" alt="Sad
" width="15" height="15" border="0">For Example : 50,24,34,6)
<input type='button' value='Calculate' onclick="resultt()">
<label><b>Result</b>:</label><input name='' type='text' id='res' readonly='readonly' >
</body>
</html>
Output :