Why is the output of this expression 20?
I've tried different calculations but it always leads to the output of 24.
Could some please explain to me how Javascript calculates this expression?
Thank You.
let A = 2;
let B = 4;
let result = B + B * A + 8;
console.log(result);
Output: 20
It follows the rule of PEMDAS (which stands for Parathesis, Exponents, Multiplication and Division, Addition and Subtraction).
What this simply means is that multiplication and division has a "higher" order than addition or subtraction. Which means multiplication and division will take place first before any addition or subtraction.
It's evaluating like this:
result = 4 + 4 * 2 + 8
Because of point before line calculation, a parenthesis is placed around the multiplication.
Like this: 4 + (4 * 2) + 8
Which evaluates to 4 + 8 + 8, and you can't that's 20.
Maybe your calculator didn't do point before line calculation.
Hope I could help.
I hope this helps to understand
let A = 2;
let B = 4;
let result = (B + B) * A + 8;
console.log(result); //Outputs 24
A = 2;
B = 4;
result = B + (B * A) + 8;
console.log(result); //Outputs 20
Related
For an odds calculator for a board game, I need to calculate how many rounds a battle will last on average. Because there is a possibility that both sides in the battle will miss, a battle can theoretically last forever. Therefore I cannot traverse all branches, but need to calculate a mathematical limit. By verifying with a simulator, I have found that the following function correctly approximates the average number of rounds left:
// LIMIT could be any number, the larger it is, the more accurate the result.
const LIMIT = 100;
// r is the number of rounds left if at least 1 of the sides hit
// x is the chance that both sides miss and the round count gets increased,
// but the battle state stays the same.
function approximateLimitForNumberOfRounds(r: number, x: number) {
let approx = r / (1 - x);
// n -> infinity
for (let n = 1; n < LIMIT; n++) {
approx += x ** n;
}
return approx;
}
How can I modify this function to exactly calculate the number of rounds left, instead of approximating it? (noting that since x is a chance, it is contained in (0, 1) or 0 < x < 1).
We can note that approx takes on the following values:
r / (1 - x) # I refer to this as 'a' below
a + x
a + x + x^2
a + x + x^2 + x^3
a + x + x^2 + ... + x^n
Thus, we can simplify the mathematical expression to be:
a + (the sum of x^k from k = 1 to k = n)
Next, we must note that the sequence x + x^2 + x^3 ... forms a geometric sequence with first term x and common ratio x. Since x is bounded by 0 < x < 1, this will have a limiting sum, namely:
x + x^2 + x^3 + ... x^inf = x/(1-x)
(this obviously fails when x = 1, as well as in the original function where r / (1 - x) is taken, but in that case, you will simply have the sum as infinity and approx would escape to infinity if it were not undefined; so I am assuming that x != 1 in the following calculations and x = 1 can be / has been dealt with separately).
Now, since we have both a single expression for x + x^2 + ... to infinity, and a single expression for approx that includes x + x^2 + ... then we can write approx using both of these two facts:
approx = r / (1 - x) + x / (1 - x)
approx = (r + x) / (1 - x)
And there you go! That is the mathematical equivalent of the logic you've outlined in your question, compressed to a single statement (which I believe is correct :)).
I've started with some problems on HackerRank, and am stuck with one of the Project Euler problems available there.
The problem statement says: Find the sum of all the multiples of 3 or 5 below N
I've calculated the sum by finding sum of multiple of 3 + sum of multiples of 5 - sum of multiples of 15 below the number n
function something(n) {
n = n-1;
let a = Math.trunc(n / 3);
let b = Math.trunc(n / 5);
let c = Math.trunc(n / 15);
return (3 * a * (a + 1) + 5 * b * (b + 1) - 15 * c * (c + 1)) / 2;
}
console.log(something(1000)); //change 1000 to any number
With the values of num I've tried, it seems to work perfectly, but with two out of five test cases there, it returns a wrong answer (I can't access the test cases).
My question is what is the problem with my code? as the logic seems to be correct to me at least.
Edit: Link to problem page
Some of the numbers in the input are probably larger than what javascript can handle by default. As stated in the discussion on the hackkerrank-site, you will need an extra library (like: bignumber.js) for that.
The following info and code was posted by a user named john_manuel_men1 on the discussion, where several other people had the same or similar problems like yours
This is how I figured it out in javascript. BigNumber.js seems to store the results as strings. Using the .toNumber() method shifted the result for some reason, so I used .toString() instead.
function main() {
var BigNumber = require('bignumber.js');
var t = new BigNumber(readLine()).toNumber();
var n;
for(var a0 = 0; a0 < t; a0++){
n = new BigNumber(readLine());
answer();
}
function answer() {
const a = n.minus(1).dividedBy(3).floor();
const b = n.minus(1).dividedBy(5).floor();
const c = n.minus(1).dividedBy(15).floor();
const sumThree = a.times(3).times(a.plus(1)).dividedBy(2);
const sumFive = b.times(5).times(b.plus(1)).dividedBy(2);
const sumFifteen = c.times(15).times(c.plus(1)).dividedBy(2);
const sumOfAll = sumThree.plus(sumFive).minus(sumFifteen);
console.log(sumOfAll.toString());
}
}
Im trying to figure out how to write a JavaScript program that computes and outputs the volume of a regular tetrahedron. This is how far I got but it seems to get a error and not compute the right numbers after.
The equation for the triangle is
v = a3
6 √ 2
Sorry about the code i dont know how to post things on here very effectively. So this is my variables
var a = parseFloat(document.getElementById('length').value);
var b = (a * a * a) / 6 * Math.sqrt(2)
You are very close. You are missing some parenthesis around 6 * Math.sqrt(2)
Your code is doing (a*a*a) / 6 and then multiplying that result by the square root of 2.
You can read up on Operator Precedence
var a = 4;
var b = (a * a * a) / (6 * Math.sqrt(2))
console.log(b);
You can also use Math.pow()
var a = 4;
var b = Math.pow(a,3) / (6 * Math.sqrt(2))
console.log(b);
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.
I Want to round 1.006 to two decimals expecting 1.01 as output
When i did
var num = 1.006;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2)); //Output 1.01
Similarly,
var num =1.106;
alert(Math.round(num,2)); //Outputs 1
alert(num.toFixed(2));; //Outputs 1.11
So
Is it safe to use toFixed() every time ?
Is toFixed() cross browser complaint?
Please suggest me.
P.S: I tried searching stack overflow for similar answers, but could not get proper answer.
EDIT:
Why does 1.015 return 1.01 where as 1.045 returns 1.05
var num =1.015;
alert(num.toFixed(2)); //Outputs 1.01
alert(Math.round(num*100)/100); //Outputs 1.01
Where as
var num = 1.045;
alert(num.toFixed(2)); //Outputs 1.04
alert(Math.round(num*100)/100); //Outputs 1.05
Try something like...
Math.round(num*100)/100
1) Multiple the original number by 10^x (10 to the power of x)
2) Apply Math.round() to the result
3) Divide result by 10^x
from: http://www.javascriptkit.com/javatutors/round.shtml
(to round any number to x decimal points)
This formula Math.round(num*100)/100 is not always good. Example
Math.round(0.145*100)/100 = 0.14
this is wrong, we want it to be 0.15
Explanation
The problem is that we have floats like that
0.145 * 100 = 14.499999999999998
step one
so If we round, we need to add a little bit to our product.
0.145 * 100 + 1e-14 = 14.500000000000009
I assume that sometimes the product might be something like 1.000000000000001, but it would not be a problem if we add to it, right?
step two
Calculate how much should we add?
We know float in java script is 17 digits.
let num = 0.145
let a = Math.round(num*100)/100
let b = a.toString().length
let c = 17-b-2
let result = Math.round(num*100 + 0.1**c)/100
console.log(result)
console.log('not - ' + a )
(-2) - is just to be sure we are not falling into the same trap of rounding.
One-liner:
let num = 0.145
let result = Math.round(num*100 + 0.1**(17-2-(Math.round(num*100)/100).toString().length))/100
Extras
Remember, that everything above is true for positive numbers. If you rounding negative number you would need to subtract a little bit. So the very final One-liner would be:
let num = -0.145
let result = Math.round(num*100 + Math.sign(num)*0.1**(17-2-(Math.round(num*100)/100).toString().length))/100
I realize this problem is rather old, but I keep running into it even 5 years after the question has been asked.
A working solution to this rounding problem I know of is to convert the number to a string, get the required precision number and round up or down using math rules.
An example where Math.round provides unexpected rounding and an example of string rounding can be found in the following fiddle:
http://jsfiddle.net/Shinigami84/vwx1yjnr/
function round(number, decimals = 0) {
let strNum = '' + number;
let negCoef = number < 0 ? -1 : 1;
let dotIndex = strNum.indexOf('.');
let start = dotIndex + decimals + 1;
let dec = Number.parseInt(strNum.substring(start, start + 1));
let remainder = dec >= 5 ? 1 / Math.pow(10, decimals) : 0;
let result = Number.parseFloat(strNum.substring(0, start)) + remainder * negCoef;
return result.toFixed(decimals);
}
let num = 0.145;
let precision = 2;
console.log('math round', Math.round(num*Math.pow(10, precision))/Math.pow(10, precision));
// 0.145 rounded down to 0.14 - unexpected result
console.log('string round', round(num, precision));
// 0.145 rounded up to 0.15 - expected result
Math.round doesn't work properly here because 0.145 multiplied by 100 is 14.499999999999998, not 14.5. Thus, Math.round will round it down as if it was 14.4. If you convert it to a string and subtract required digit (5), then round it using standard math rules, you will get an expected result of 0.15 (actually, 0.14 + 0.01 = 0.15000000000000002, use "toFixed" to get a nice, round result).