Hello there,
I was attacking Project Euler, problem 26:
"Find the value of d <1000 for which 1/d contains the longest recurring cycle in its decimal fraction part."
I was trying to find the length of the repetend for each 1/d by calculating the smallest k for which 10แต mod d == 1 but was getting weird/wrong results, e.g.
var mathjs = require('mathjs');
mathjs.config({
number: 'BigNumber',
precision: 4096
});
var p = mathjs.chain(10)
.pow(58)
.mod(531)
.done();
console.log(mathjs.format(p));
/*
Expected answer: 1
Actual answer: 0
*/
The expected answer is 1, per https://www.wolframalpha.com/input/?i=10%5E58+mod+531 but it's returning 0?
Reproduction with a more obviously wrong result:
(...)
var p = mathjs.chain(10)
.pow(16)
.mod(3)
.done();
console.log(mathjs.format(p));
/*
Expected answer: 1
Actual answer: 0
*/
The greatest power of 10 for which mod(3) gives the correct answer is 15.
Is there something I'm doing wrong here?
Whilst you configure to use BigNumbers, in chain you use regular numbers (which have a precision in the order of 16 bits which can explain this limit of 10^16).
The following works as expected, the expression parser will create BigNumbers:
mathjs.config({
number: 'BigNumber'
});
console.log(mathjs.format(mathjs.eval('(10^58) mod 531'))); // 1
or:
mathjs.config({
number: 'BigNumber'
});
var p = mathjs.chain(math.bignumber(10))
.pow(math.bignumber(58))
.mod(math.bignumber(531))
.done();
console.log(mathjs.format(p)); // 1
The bignumber configuration is confusing, it's quite logical to expect that numbers are always turned into BigNumbers which is not the case. This has bitten other people as well. Maybe we should rethink this behavior and automatically turn all numbers into BigNumbers (or Fractions) when configured like that.
Thanks for your quick answer Jos.
You're right, the current behaviour seems counterintuitive to me.
I'm jumping in late in the discussion, but I agree that regular numbers should be converted to BigNumbers automatically. Is this something typed-function can do?
I don't have a clear idea how we could best tackle this challenge, but I indeed think that this may be something we can solve by extending typed-function with capability to do preprocessing of inputs depending on dynamic configuration.
Most helpful comment
Whilst you configure to use BigNumbers, in chain you use regular numbers (which have a precision in the order of 16 bits which can explain this limit of 10^16).
The following works as expected, the expression parser will create BigNumbers:
or:
The bignumber configuration is confusing, it's quite logical to expect that numbers are always turned into BigNumbers which is not the case. This has bitten other people as well. Maybe we should rethink this behavior and automatically turn all numbers into BigNumbers (or Fractions) when configured like that.