Javascript NaN large integer error - javascript

So I was calculating last ten digit of the series :
1^1 + 2^2 + 3^3 + ... + 1000^1000
But I keep getting NaN as a result.
Code:
function myFunction() {
var i, x, a, sum = 0; {
for (i = 1; i <= 1000; i++) {
var a = Math.pow(i, i);
sum += a;
}
var x = sum;
var y = x % 10000000000;
}
document.getElementById("demo").innerHTML = y;
}
<p>Click the button to demontrate </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Math.pow(1000, 1000)
Thats a very very huge number, (3000 zeros), so javascript can't handle it, thats why the above results in Infinity. And the modulo of an infinite number cannot be determined, therefore the result is Not A Number.

You have an Infinity value - try the code below :
function myFunction() {
var i, x, a, sum = 0; {
for (i = 1; i <= 1000; i++) {
var a = Math.pow(i, i);
if(a!=Infinity)sum += a;
}
var x = sum;
var y = x % 10000000000;
document.getElementById("demo").innerHTML = y;
}

Javascript uses 64-bit floating point numbers for everything. The max value of one of those is about 1.8 × 10^308, which is quite a bit smaller than your 1000^1000 value. As a consequence, since the number it's trying to calculate can't fit into a "number"-type variable, Javascript returns NaN and leaves it at that.

Number.MAX_VALUE is the maximum number available.
Otherwise you have to use some library for example: https://mikemcl.github.io/bignumber.js/

Explanation
Big Ints (greater than (2^31 - 1) as #suhas explained) are not currently supported in JS, however there is a TC39 draft currently in stage 3 (candidate).
Solution
In the meantime, use a library such as this one.

As #jonas-w correctly pointed out, your specific problem is trying to take the modulo of an infinite number. infinity % anyNumber yields NaN.
In addition, you need to understand that floating-point values use scientific notation. That means that for large numbers, all of your significant digits (53 for IEEE 754 double-precision, which is what JavaScript uses) are at the upper end of the value, yet your modulo is examining the lower end.
For example, 1.1×10^6 is 1,100,000, and 1.2×10^6 is 1,200,000. Getting the % 100 is pointless, as both yield 0.
What are you trying to accomplish with this code?

Related

Codility Ladder javascript - not understanding a detail that jumps the answer from 37 to 100%

I'm trying to solve all the lessons on codility but I failed to do so on the following problem: Ladder by codility
I've searched all over the internet and I'm not finding a answer that satisfies me because no one answers why the max variable impacts so much the result.
So, before posting the code, I'll explain the thinking.
By looking at it I didn't need much time to understand that the total number of combinations it's a Fibonacci number, and removing the 0 from the Fibonacci array, I'd find the answer really fast.
Now, afterwards, they told that we should return the number of combinations modulus 2^B[i].
So far so good, and I decided to submit it without the var max, then I got a score of 37%.. I searched all over the internet and the 100% result was similar to mine but they added that max = Math.pow(2,30).
Can anyone explain to me how and why that max influences so much the score?
My Code:
// Powers 2 to num
function pow(num){
return Math.pow(2,num);
}
// Returns a array with all fibonacci numbers except for 0
function fibArray(num){
// const max = pow(30); -> Adding this max to the fibonaccy array makes the answer be 100%
const arr = [0,1,1];
let current = 2;
while(current<=num){
current++;
// next = arr[current-1]+arr[current-2] % max;
next = arr[current-1]+arr[current-2]; // Without this max it's 30 %
arr.push(next);
}
arr.shift(); // remove 0
return arr;
}
function solution(A, B) {
let f = fibArray(A.length + 1);
let res = new Array(A.length);
for (let i = 0; i < A.length; ++i) {
res[i] = f[A[i]] % (pow(B[i]));
}
return res;
}
console.log(solution([4,4,5,5,1],[3,2,4,3,1])); //5,1,8,0,1
// Note that the console.log wont differ in this solution having max set or not.
// Running the exercise on Codility shows the full log with all details
// of where it passed and where it failed.
The limits for input parameters are:
Assume that:
L is an integer within the range [1..50,000];
each element of array A is an integer within the range [1..L];
each element of array B is an integer within the range [1..30].
So the array f in fibArray can be 50,001 long.
Fibonacci numbers grow exponentially; according to this page, the 50,000th Fib number has over 10,000 digits.
Javascript does not have built-in support for arbitrary precision integers, and even doubles only offer ~14 s.f. of precision. So with your modified code, you will get "garbage" values for any significant value of L. This is why you only got 30%.
But why is max necessary? Modulo math tells us that:
(a + b) % c = ([a % c] + [b % c]) % c
So by applying % max to the iterative calculation step arr[current-1] + arr[current-2], every element in fibArray becomes its corresponding Fib number mod max, without any variable exceeding the value of max (or built-in integer types) at any time:
fibArray[2] = (fibArray[1] + fibArray[0]) % max = (F1 + F0) % max = F2 % max
fibArray[3] = (F2 % max + F1) % max = (F2 + F1) % max = F3 % max
fibArray[4] = (F3 % max + F2 % max) = (F3 + F2) % max = F4 % max
and so on ...
(Fn is the n-th Fib number)
Note that as B[i] will never exceed 30, pow(2, B[i]) <= max; therefore, since max is always divisible by pow(2, B[i]), applying % max does not affect the final result.
Here is a python 100% answer that I hope offers an explanation :-)
In a nutshell; modulus % is similar to 'bitwise and' & for certain numbers.
eg any number % 10 is equivalent to the right most digit.
284%10 = 4
1994%10 = 4
FACTS OF LIFE:
for multiples of 2 -> X % Y is equivalent to X & ( Y - 1 )
precomputing (2**i)-1 for i in range(1, 31) is faster than computing everything in B when super large arrays are given as args for this particular lesson.
Thus fib(A[i]) & pb[B[i]] will be faster to compute than an X % Y style thingy.
https://app.codility.com/demo/results/trainingEXWWGY-UUR/
And for completeness the code is here.
https://github.com/niall-oc/things/blob/master/codility/ladder.py
Here is my explanation and solution in C++:
Compute the first L fibonacci numbers. Each calculation needs modulo 2^30 because the 50000th fibonacci number cannot be stored even in long double, it is so big. Since INT_MAX is 2^31, the summary of previously modulo'd numbers by 2^30 cannot exceed that. Therefore, we do not need to have bigger store and/or casting.
Go through the arrays executing the lookup and modulos. We can be sure this gives the correct result since modulo 2^30 does not take any information away. E.g. modulo 100 does not take away any information for subsequent modulo 10.
vector<int> solution(vector<int> &A, vector<int> &B)
{
const int L = A.size();
vector<int> fibonacci_numbers(L, 1);
fibonacci_numbers[1] = 2;
static const int pow_2_30 = pow(2, 30);
for (int i = 2; i < L; ++i) {
fibonacci_numbers[i] = (fibonacci_numbers[i - 1] + fibonacci_numbers[i - 2]) % pow_2_30;
}
vector<int> consecutive_answers(L, 0);
for (int i = 0; i < L; ++i) {
consecutive_answers[i] = fibonacci_numbers[A[i] - 1] % static_cast<int>(pow(2, B[i]));
}
return consecutive_answers;
}

Modulo % with big number- Infinity error - Javascript [duplicate]

This question already has answers here:
Calculating pow(a,b) mod n
(14 answers)
Closed 6 years ago.
Is there are trick to get the modulo of big numbers in Javascript. I am getting infinity with modulo(7, 16971, 25777) 7^16971mod25777=NaN
function modulo (n, p, m){
var x = Math.pow(n, p);
var y = m;
var z = x%y;
alert(x);
return z;
}
There's a mathematical "trick" you can use, if you can assume all parameters are integers.
Consider the following modulo operation:
(a*x + y) % x
Obviously, the a*x part can be discarded and the following holds:
(a*x + y) % x = y % x
With that in mind we can assume the big number is just a*x + y, and we can perform the modulo at any stage, and as often as we like, so, to get the result you want, do this:
function modulo (n, p, m){
var result = 1;
while(p--) {
result = (result * n) % m;
}
return result;
}
console.log(modulo(7, 16971, 25777));
JavaScript numbers are stored as 64-bit floats.
Math.pow(7, 16971) is Infinity because the value is too large for that representation. Specifically, it's larger than Number.MAX_VALUE, which is 1.7976931348623157e+308.
The largest safe integer is Math.pow(2, 53) - 1), aka Number.MAX_SAFE_INTEGER.
You can use an arbitrary size integer library like big-integer to work with larger integers:
const result = bigInt(7).modPow(16971, 25777);
console.log(result.value); // 857
JSFiddle
You'll probably want to look into a large number library such as big.js to do this. It has its own mod() function to handle larger numbers and greater floating point precision.
From the manual:
1 % 0.9 // 0.09999999999999998
x = new Big(1)
x.mod(0.9) // '0.1'
Please try this, it should work for you...
<script src="http://peterolson.github.com/BigInteger.js/BigInteger.min.js"></script>
<script>
function modulo(n, p, m) {
var x = bigInt(n).pow(p);
var y = m;
var z = bigInt(x).mod(y);
alert(x);
alert(z);
return z;
}
modulo(7, 16971, 25777);
</script>
Value of X= ( 144157446840451635235083706110907852415749228859252529148906391999766994677256648514596635518338118874745245599504027645569205474259056773767697690363704468632892152795016715055324575445087682781252313005869045568884109150825799944546337893064300709178398146710515468212610079448225972249066488499049225372747076806433631659786194988344294497773759564575000162869574365014937829611100108282508068839769488427218809418476143641444334160948843097387146975458980549194883596975058014553601039150039974922599124812752683319818785474747861041069869797998022819369652619759825244859686407688179575508679861543683676353692931928781365284923967762962761189903683793268647203089135578161089792845634056425105473120490657724974694040110140134504449715061852058159494813855440466218772852172975097582562908895057311050472869260715192269051794091102837753073541384982827121618414372575452344004360364276677087398549812260325448141226947881328515773351976616276417638128022815680053293310617319251468387901625157...56951333749257599033126883342183151178668919812064049965349560466150682525651094508048667165975539000764644172767648163518366194953573817885103167718630743142062623550549541359220427411352708364483389060986844929269143259135008252906461288098421933603373774514126347477000279431329468363160423511545129487503178839098880369937328996412126931687097210220191726087729442555830870326323512951767388505151559227624666317971526350895004302090730198002124799887057180493028281166853990182770936726392403645367304961828645095221020100469965292184204520213166368848723223621651107654075062116217744242552262031457878341343131239324794711518591327361143916482110866686618572491075943511233044928342441933757654662089762470943194596874717623496819342403306038522266428198018364568515908102686200233757394776127456240030822204960242512397946554388855232832783930954979762030089547004776120626513910030444279665047610388454114197939348310563226006027400434616239674784018828580353008938225035036985223336494743), please take a look at output screen below.
Value of Z=(857). please take a look at output screen below.

How to write a program that print bits of integer in JS

How to write a program that print out bits of integer.
I'm trying to do something like that:
function countBits(octet)
{
var i;
var c = "";
var k = "";
i = 128;
while (i > 0)
{
c = "";
if (octet < i)
{
c = '0';
i = i / 2;
k += c
}
else
{
c = '1';
k += c
octet = octet - i;
i = i / 2;
}
}
return k;
}
But if I trying to print bits with this program I have Output:
Input: 123
Output 01111011 and infinity numbers of zero
How can I remove this bug?
P.S: I want to do this program using only loops and algorithms, NOT function like (n >>> 0).toString(2); or .map() or something like this
Your variable i is always greater than 0, so the while loop keeps running forever. When you decrement it, you halve it. That will never get to 0, however it will get to a value smaller than one, and at this point you want to stop.
Try using while (i >= 1) instead as your condition.
So i added a little logging for checking the values of i and I got this in the loop:
i = 64; i = 32; i = 16; ... i = 1; i = 0.5; i = 0.25
So yeah, do what AgataB said with regards to using another condition instead since for javascript,
1 / 2 does not give you 0.
Unlike many other programming languages, JavaScript does not define
different types of numbers, like integers, short, long, floating-point
etc.
JavaScript numbers are always stored as double precision floating
point numbers, following the international IEEE 754 standard.
Quoted from: http://www.w3schools.com/js/js_numbers.asp

Codefights: Correct solution but system does not accept it

Experienced codefighters, i have just started using Codefight website to learn Javascript. I have solved their task but system does not accept it. The task is to sum all integers (inidividual digit) in a number. For example sumDigit(111) = 3. What is wrong with my code? Please help me.
Code
function digitSum(n) {
var emptyArray = [];
var total = 0;
var number = n.toString();
var res = number.split("");
for (var i=0; i<res.length; i++) {
var numberInd = Number(res[i]);
emptyArray.push(numberInd);
}
var finalSum = emptyArray.reduce(add,total);
function add(a,b) {
return a + b;
}
console.log(finalSum);
//console.log(emptyArray);
//console.log(res);
}
Here's a faster trick for summing the individual digits of a number using only arithmetic:
var digitSum = function(n) {
var sum = 0;
while (n > 0) {
sum += n % 10;
n = Math.floor(n / 10);
}
return sum;
};
n % 10 is the remainder when you divide n by 10. Effectively, this retrieves the ones-digit of a number. Math.floor(n / 10) is the integer division of n by 10. You can think of it as chopping off the ones-digit of a number. That means that this code adds the ones digit to sum, chops off the ones digit (moving the tens digit down to where the ones-digit was) and repeats this process until the number is equal to zero (i.e. there are no digits left).
The reason why this is more efficient than your method is that it doesn't require converting the integer to a string, which is a potentially costly operation. Since CodeFights is mainly a test of algorithmic ability, they are most likely looking for the more algorithmic answer, which is the one I explained above.

Fibonacci sequence results in infinity, then NaN

I was playing around with writing a javascript Fibonacci sequence, as I had never tried to do so, came up with an easy iterative formula to calculate it. Then I decided to test run it by doing 10000 iterations to see the results. to my surprise, it worked until the 1476th iteration, then broke. 1477 and 1478 both gave the result "Infinity". I have tried different browsers, changing the methods for display, but ended up with the same results.
1475i - 1.3069892237633983e+308
1476i - Infinity
1477i - Infinity
1478i - NaN
Code used:
<!DOCTYPE html><html><head><script>
function fibonacci(){
var x = 1;
var y = 0;
for(i=0;i<1478;i++){
var box = document.createElement('div');
box.setAttribute('id','box'+i);
document.body.appendChild(box);
document.getElementById('box'+i).innerHTML = [i] + 'i - ' + x;
x = x + y;
y = x - y;
}
}
</script></head><body onLoad="fibonacci();"><div id="output"></div></body></html>
I am not sure if then function broke at a certain point, or what I may have failed to take into accountof in the sequence. And yes, I realize that I skipped the first integer, but that shouldn't affect the function.
The 1477th Fibonacci number is too big to be represented by Javascript. The "overflow" causes your number to become Infinity.
Infinity - 1476thFibonacciNumber is still Infinity in the following y calculation.
Then on the next iteration you have Infinity - Infinity which is NaN in JavaScript. From that point, it's NaN all the way to the end.
The largest value Javascript can handle is 1.7976931348623157e+308. If your code generates anything larger than this it will break.
For large values of N, the Fibonacci series can be approximated by
F(N) = math.pow(phi, N) / math.sqrt(5)
(ref: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#fibround )
Where phi is the golden ratio: (sqrt(5)+1)/2
You can now figure out what the largest Fibonacci number is that you can calculate with the following:
phi = (math.sqrt(5)+1)/2
fibMax = math.floor(log(1.79769)/log(phi) + math.log(math.sqrt(5)))
And the answer from the above is... 1475 - which is the largest number you were able to compute without overflow.
Bottom line - once your calculation overflows, it will continue to do so. Infinity + anything = Infinity, and interestingly Infinity - anything = still infinity. And infinity + infinity = NaN. So even if you subtracted the last number off again, you would not get back to a "real" number. That's just how overflow is treated.
On the subject of the Fibonacci sequence in JavaScript. MDNhas a good example using generators:
// Declare generator
function* fibonacci() {
let n0;
let n1 = 0
let n2 = 1
while (true) {
n0 = n1
n1 = n2
n2 = n0 + n1
yield n0
}
}
// Create generator
var y = fibonacci()
// Print them out
for (let x = 0; x < 1477; x++) {
console.log(x + 1, " ", y.next().value)
}

Categories