2

I use math.js to calculate gcd for a series of numbers wich are taken from input. Among the tested options I mention:

  • parseInt() and parseFloat()
  • IaNr=document.getElementById("nrs").value
  • math.gcd(nrs.value);
  • math.gcd($("#nrs").val())
  • IaNr.toString()

but it doesn't work. what am I missing, because it doesn't calculate the numbers from input. it works when I provide the numbers directly. ex: math.gcd(4, 8, 25,74)

<script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/1.2.0/math.min.js"></script>  

$(function(){

IaNr=$("#nrs").val()

DoGcd=math.gcd(IaNr)

$("#show").html(DoGcd)
})          

<input id="nrs"  value="14,92,34,78">

<div id="show"></div>
ChrisGP
  • 427
  • 1
  • 4
  • 11

3 Answers3

1
var arr = $("#nrs").val();
var array  = arr.split(',');
for(var i=0 ; i< array.length ;i++){
array[i] = parseInt(array[i]);
}

dogcd = math.gcd(array[0],array[1],array[2],array[3]);
$("#show").html(dogcd);
praveenraj
  • 774
  • 1
  • 9
  • 20
  • thx this ia a partial solution, because in the final version there won't be a fixed set of numbers. In the Input people will be able to insert from 2 up to 10 numbers for which to calculate the gcd. – ChrisGP Jan 24 '15 at 08:17
  • switch array.length : {make cases for 2 to 10} – JMP Jan 24 '15 at 09:20
0
IaNr = $.map($("#nrs").val().split(','),
    function(val, idx) { 
         return parseInt(val, 10);
    })

DoGcd=math.gcd(IaNr);

$("#show").html(DoGcd);

Demo

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
0

I build on the solution suggested by @praveenraj9:

var arr = $("#nrs").val();
var array  = arr.split(',');
for(var i=0 ; i< array.length ;i++){
array[i] = parseInt(array[i]);
}

and adapted to suit my needs.

 FaL=arr.length;
 if(FaL===2){$("#show").html(math.gcd(ar[0],ar[1]))};
 if(FaL===3){$("#show").html(math.gcd(ar[0],ar[1],ar[2]))}
 etc

if anyoane knows a more elegant / shorter solution I welcome it.

thx for your help.

ChrisGP
  • 427
  • 1
  • 4
  • 11