-1

Why different output?

I tried to resolve this problem and I can't with javascript only using python, what is wrong is '%' different in javascript?

I use '%' to get last 10 digits from the result.

Javascript:

const puzzle = (N, P) => {
      var A = 1,
        B = 1,
        C = 1,
        D = 1,
        X;

      for (var j = 0; j < P; j++)
        for (var i = 0; i < N; i++) {
          X = D + 2 * C + 3 * B + 4 * A;
          A = B;
          B = C;
          C = D;
          D = X;
        }

      return D % 10000000000;
    };

    console.log(puzzle(10, 1));
    console.log(puzzle(100, 1));
    console.log(puzzle(2022, 100));

Python:

def puzzle(N, P):
    A = 1;
    B = 1;
    C = 1;
    D = 1;
    X = 0;

    for ea in range(P):
      for esa in range(N):
          X = D + 2 * C + 3 * B + 4 * A;
          A = B;
          B = C;
          C = D;
          D = X;
        
    return D % 10000000000;
  
  
print(puzzle(10, 1));
print(puzzle(100, 1));
print(puzzle(2022, 100));

Output (Python):

> 30520
> 720820623
> 5553751141
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Luka
  • 11
  • 1
  • 2
    Hint: log (or use a debugger to inspect) the value of `D` before returning `D % …`. – Ry- May 25 '22 at 02:47
  • 1
    Welcome to Stack Overflow. "Why does this code in language X not do the same thing as this other code in language Y?" questions are not actually about language Y. It would be better to explain *what the code is supposed to do*, what actually appears to happen, and how that is different, using plain English. Please also try to [investigate](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) what is going wrong yourself, for example by comparing the behaviour each time through the loop and checking where it first gives a different result. – Karl Knechtel May 25 '22 at 02:48

1 Answers1

0

You are simply playing with too big numbers for number primitive.
Fortunately, there is a solution.

To understand it correctly, nothing is best than reading the documentation about BigInt.

console.clear();

const puzzle = (N, P) => {
  var A = BigInt(1),
    B = BigInt(1),
    C = BigInt(1),
    D = BigInt(1),
    X = BigInt(1);

  for (var j = 0; j < P; j++)
    for (var i = 0; i < N; i++) {
      X = D + BigInt(2) * C + BigInt(3) * B + BigInt(4) * A;
      A = B;
      B = C;
      C = D;
      D = X;
    }

  return Number(D % BigInt(10000000000));
};

console.log(puzzle(10, 1));
console.log(puzzle(100, 1));
console.log(puzzle(2022, 100));
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
  • Note that you can (and should) write `BigInt` literals as `1n` instead of `BigInt(1)`, which is important because the constructor form silently gives the wrong results when the input gets big enough. – Ry- May 25 '22 at 05:28