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
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));