Skip to content Skip to sidebar Skip to footer

Least Significant Non-zero Digit Of A Factorial

I am trying to calculate the least significant non-zero digit in a factorial. I have the following snippet : As part of the above code, to calculate the least significant non-ze

Solution 1:

The problem is that 5's don't simply disappear. They combine with a 2 to create a 0. So you'll have problems after multiples of 5 (like 15 or 35) or after numbers with a lot of powers of 2 (like 24). The best thing might be to keep count of the number of 2's, and decrease that for each multiple of 5 (there's always more 2's than 5's). (Also, once you've gone to the trouble of finding the number without a 0, you don't need to convert it to a string.)

$(document).ready(function() {
  $('#submit').click(function() {
    var n = $('#number').val();
    get_result(n);
  });
});

functionget_result(n) {
  var factorial = 1;
  var factorial2 = 1;
  for ( var i = 1; i <= n; i++ ) {
    factorial = factorial * i;
  }
  var extra2s = 0;
  for ( var j = 1; j <= n; j++ ) {
    var jcopy = j;
    while( jcopy%10 == 0 ) {
      jcopy /= 10;
    }
    while( jcopy%2==0 ) {
      extra2s++;
      jcopy /= 2;
    }
    while( jcopy%5==0 ) {
      extra2s--;
      jcopy /= 5;
    }
    jcopy %= 10;
    factorial2 = (factorial2 * jcopy)%10;
  }
  for ( var k = 0 ; k < extra2s ; k++ ) {
    factorial2 = (factorial2 * 2)%10;
  }
  var digit = factorial2;
  $('#display').text("Factorial of " + n + " is " + factorial);
  $('#display2').text("Least significant digit of Factorial of " + n + " is " + digit);
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="display"></div><divid="display2"></div><inputtype="text"value=""id="number"><inputtype="submit"id="submit">

Post a Comment for "Least Significant Non-zero Digit Of A Factorial"