0

I made a NodeJS program that takes pairs of integers (m, n) as input and prints the sum of their factorials (facm, factn) on the console. I used the BigInteger.js library so that I can calculate using big numbers.

But when I input 20 1, the program just outputs the value of 20! instead of 20! + 1!. It doesn't add. Why?

(For some reason, it works for when the two inputs are the same, for example, 20 20. It also works when the values are smaller.)

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var bigInt = require("big-integer");

for (var i = 0; lines[i] != ""; i++) { 
    var strings = lines[i].split(" ");
    var m = parseInt(strings[0]);
    var n = parseInt(strings[1]);
    var factm = bigInt(1);
    var factn = bigInt(1);
    for (var a = m; a != 0; a--) {
        factm = factm.multiply(a);
    }
    for (var b = n; b != 0; b--) {
        factn = factn.multiply(b);
    }
    var sum = factm.add(factn);
    console.log(sum.toString());
}
zadspecial
  • 13
  • 3
  • 1
    What are the final values of the two `fact` variables before addition? – Carcigenicate May 18 '18 at 12:37
  • 1
    I can't reproduce in in [JSFiddle](https://jsfiddle.net/16okocg3/1/). Are you sure there is nothing wrong with the data? – SergGr May 18 '18 at 12:54
  • @Carcigenicate They are 20! and 1!. I checked those with different values. They are alright. It's only the addition that doesn't work. – zadspecial May 18 '18 at 13:05
  • @SergGr I checked out JSFiddle and couldn't find NodeJS support in it. That's probably why it didn't work for you. I'm certain there's nothing wrong with the data. I checked with different values. – zadspecial May 18 '18 at 13:06
  • @zadspecial, technically browser is different from NodeJS but I'd be very surprised if there is a bug that is NodeJS-specific and it is just easier to try in a browser in a thing like JSFiddle. Is it true that if you run just the code from the fiddle (+ `require`) instead of your loop and input/output in your local NodeJS , you still get the wrong answer (i.e. different from the fiddle)? – SergGr May 18 '18 at 13:09
  • @SergGr I *just* checked the JSFiddle link you commented. It works. And this is actually a problem on http://urionlinejudge.com.br/. I submitted the code there and they said Wrong Answer (10%). But after I fixed the code (see my answer), they accepted the code. So everything's good now. – zadspecial May 19 '18 at 23:14

1 Answers1

0

Replacing var sum = factm.add(factn) with var sum = factm.add(factn.toString()) solves the problem.

zadspecial
  • 13
  • 3