I was making a summation algorithm to add 2 very big numbers.
//input
let n1 = 1234567891234556555558
let n2 = 1234567891234556555558
//processing
let a = n1.toString()
let b = n2.toString()
let c = 0 //carry
let r = '' //final result of summation
for (let i = 1; i <= Math.max(a.length, b.length); i++) {
if(a.length == b.length) {
let v = parseInt(a[a.length - i]) + parseInt(b[b.length - i]) + c; c = 0
if(v.toString().length == 1) {
r = v + r.slice(0, r.length)
}
else {
r = parseInt(v.toString()[1]) + r.slice(0, r.length)
c = parseInt(v.toString()[0])
}
}
}
//output
console.log(r)
The code works for small values but returns a NaN for big values.
I tried to change how the c is declared, I thought it might be still a string but the result is still the same.
Please note the algorithm only works for numbers of the same length.