0
Code running extremely slowly
Hi, in my program i am trying to make a decimal to binary converter, but whenever I run, it runs very slowly. Its probably a dumb mistake but all help is appreciated. https://code.sololearn.com/WkFlKX1r0buT/#js the code
3 Antworten
+ 3
Your code doen't run extremely slowly but do infinite loop in most of cases ^^
You've two big mistakes in your main 'while' loop condition (testing if 'decimal' >= 0 instead of 'power' >=0) and your first 'if' condition inside it (Math.pow(2, power) >= decimal instead of Math.pow(2, power) <= decimal)...
Anyway, you could be more efficient by avoiding power of 2 computing many times, and you could use 'input' event rather than 'change' event (first one is fired as soon as input value is modified, while second is only fired when input value have changed after input have loose focus (require user to click elsewhere)...
However, that's not the best way to do conversion to binary (if we forgot the built-in ability of .toString() method to handle it)... Real better efficient way would be to integer divide 'decimal' by 2 until 'decimal' is different of zero, keeping reminder at each iteration in 'binary' from right to left (instead of computing binary digits from left to right). Simplest way would be:
var binary = "";
var reminder;
while (decimal != 0) {
reminder = decimal % 2;
decimal = (decimal - reminder) / 2;
binary = reminder + binary;
}
... and advanced way would be:
var binary = "";
var reminder;
while (decimal != 0) {
reminder = decimal & 1;
decimal = decimal >> 1;
binary = reminder + binary;
}
... or shorthanded:
var binary = "";
while (decimal != 0) binary = (decimal & 1) + binary, decimal >>= 1;
... by the way, that's just for the exercise, because you could simply do:
var binary = decimal.toString(2);
+ 2
Let's use 30 as an example. The first while loop will go down to 2 to the 5th, which is 32, but because your loop condition is while it is greater than, it will subtract one more from power: power--;
The next loop will go until decimal is is below 0, but the if else starts with this check: if(Math.pow(2, power)) >= decimal. Using 30 as the decimal, as I said above, the power was reduced to 4, so else will be called for infinity and decimal will never be reduced until power is -6. Look up decimal to binary converters because there's a simpler way to do this and you will probably learn a lot :)
0
Thanks a lot visph and zeke!! I am still very now to coding and these helped a lot