infinite while loop in javascript - javascript

My problem question as in the practice course goes as follows:
Write a JavaScript program to create a function which takes 2 integers as inputs. The function divides the first integer with second integer as long as the result (Quotient) is an integer (i.e. remainder is zero) and return the quotient as result. Your output code should be in the format console.log("Result is ", variableName)
And below is my code:
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
function divide(x, y) {
var result;
if (d === 1) {
result = num;
} else {
while (num % d === 0) { //while error
result = num / d;
}
}
return result;
}
var output = divide(num, d);
console.log("Result is: ", output);
If I remove the while loop, program works fine but the problem description says I have to use it.
What am I doing wrong?

There are a few issues:
1) If your function receives the arguments x and y, then use those inside his scope, don't access the global variables.
2) You are never changing the variables that are evaluated on the while condition, so the evaluation will be the same, ever!
3) Another good thing you can do is add some validation on the received arguments.
Now, your code, can be rearranged to this one:
function divide(x, y)
{
if (isNaN(x) || isNaN(y))
return "Invalid arguments!";
if (y === 1)
return x;
while (x % y === 0)
{
x = x / y;
}
return x;
}
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
var output = divide(num, d);
console.log("Result is: ", output);

Your while loop is depending of num, but you donĀ“t assign a new value to it after a cycle. This lead to that the condition stays always the same.
var num = prompt("Enter number to divide");
var d = prompt("Enter divisor");
function divide(x, y) {
var result = x;
if (y === 1) {
return result;
} else {
while (result % y === 0) {
result = result / y;
}
}
return result;
}
var output = divide(num, d);
console.log("Result is: ", output);

Related

How to calculate the factorial of a number entered by user in Javascript, using, do-loop, while-loop?

Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
<script>
var numbers = prompt("Enter a number 1-100");
while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
numbers = prompt("Try again.Enter a number 1-100");
}
if (numbers !=null){
alert("Finally you entered a correct number");
var sum = 0;
var numOfLoops = numbers;
var counter = 1;
do {
sum+=counter;
counter++;
}
while (counter<=numOfLoops)
alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
</script>
</head>
<body>
<script>
document.write("<h1>Sum of Numbers</h1>");
document.write("The sum of numbers from 1 to = " + numbers + " is = " +
+ sum + "<br><br>");
</script>
</body>
</html>
If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.
If you want to sum using the loop, just change the *= to +=.
While Loop Approach
const fact = (n) => {
let res = 1;
while (n > 0) {
res *= n;
n--;
}
return res;
}
fact(5) // 120
Do While Approach
const fact = (n) => {
let res = 1;
do {
res *= n;
n--;
} while (n > 0)
return res;
}
fact(3) // 6
That should do the trick. :)
Maybe also considering checking for edge cases like if the n is negative.
Good luck.
While Loop:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
while(n) r *= n--
return r
}
Do While:
const fact=n=>
{
if(n<0) throw 'factorial error on a negative number!'
let r = 1
do r *= n || 1 // in case of n == 0
while (n--)
return r;
}
complete code
const
msgPrompt_1 = 'Please enter a number from 0 to 100',
msgPrompt_n = 'Try again.... Enter a number 0-100',
fact = n =>
{
let r = 1
while(n) r *= n--
return r
}
let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10)
while(isNaN(numValue) || numValue > 100 || numValue < 0)
{
numValue = parseInt(window.prompt(msgPrompt_n, ''), 10)
}
alert(`factorial value of ${numValue} is = ${fact(numValue)}` )

application spits the numbers back at me even though it should return another value

I'm trying to make this front end web application where you provide acres and karats in a prompt in this form e.g. 3.22 and calculates them and give the total back in the chrome JS console
For example, you have 3.22 acres of land and another land that is 2.2 acres. If you get the sum of these numbers it should give you 5.42, no I want them to return 6, because acres have 24 karats and if you calculate 3 acres and 22 karats + 2 acres and 2 karats it should give you 6 acres, that's what I'm trying make here. I've been trying all night and every time the numbers I put in the prompt gets spit back at me in the console, so here's my code:
window.setTimeout(function() {
var acres = [];
var floats = [];
var wholes = [];
var input = prompt("What would you like to do?");
while (input !== "quit") {
if (input === "total") {
console.log("***********");
acres.forEach(function(total, i) {
console.log(i + ": " + total);
})
console.log("***********");
} else if (input === "calc") {
var num = prompt("Please enter a number");
while (num !== "back") {
if (num === "back") {
break;
}
acres.push(num);
var ftotal = 0
var wtotal = 0;
floats = [];
wholes = [];
for(var i = 0; i < acres.length; i++) {
alert("entered the for loop");
var acresNum = acres.pop();
var str = acresNum.toString();
var number = Math.floor((str).split(".")[1]);
floats.push(number);
ftotal += floats[i];
//-------------------------
var num2 = Math.floor(acresNum);
wholes.push(num2);
wtotal += wholes[i];
}
alert("exited the for loop");
console.log(ftotal);
console.log(wtotal);
if (ftotal > 23) {
wtotal++;
}
acres.push(wtotal + "." + ftotal);
var num = prompt("Please enter a number");
}
}
var input = prompt("What would you like to do?");
}
console.log("OK, YOU QUIT THE APP");}, 500)
The whole logic in this application is in that for loop in the else if(input === "calc") area.
You could take a numerical approach, but you went into the trap of floating point arithmetic (Is floating point math broken?) and get a number which does not match the given value of 42.
function sum(a, b) {
var s = a + b,
i = Math.floor(s),
p = (s - i) * 100;
console.log(p);
if (p >= 42) { // never reached
p -= 42;
++i;
}
return i + p / 100;
}
console.log(sum(3.22, 2.2));
As solution, you could separate the places as a string and add integer values and check if the value is greater than one acre, then return an adjusted value.
function sumD(a, b, threshold) {
return [a, b]
.map(v => v.toString().split('.'))
.reduce((r, a) => {
a.forEach((v, i) => r[i] += +v);
r[0] += Math.floor(r[1] / threshold);
r[1] %= threshold;
return r;
}, [0, 0])
.join('.');
}
console.log(sumD(3.22, 2.2, 24));
Separate the decimal values from your numbers.(Already done)
Ex: 3.22 -> 0.22 and 2.2 -> 0.2
Add them -> 0.22 + 0.2
Divide them by 0.24 -> (0.22+0.2)/.24 = 1
Add that to the wtotal -> 3.00 + 2.00 = 5 -> 5 + 1
I think this should be the logic mathematically.

Determining factorial of a number

I'm new to javascript and I'm having a hard time figuring out how to get this factorial function to work. Here's my code now.
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of" + x + "is" + result);
Thanks for the help!
your base case is wrong for a recursive factorial. change it to
function fact(x) {
if (x <= 1) {
return 1
}
else {
return (x * fact(x-1))
}
}
Your definition of factorial is wrong. The traditional recursive definition of factorial is:
F(x) => x == 1 ? 1 : x * F(x-1)
Or you can use the iterative definition
F(x) => var i = 1; for (j = 1..x) i = i * j
In javascript, the recursive version would be:
function factorial (x) {
if (x == 1) return x;
return x * factorial(x-1);
}
The iterative version would be:
function factorial (x) {
var result = 1;
for (var y = 1; y <= x; y++) {
result = result * y;
}
return result;
}
You can add the negative number check in the above functions. But in my opinion that would obscure the purpose of the function (which is to implement the traditional definition of factorial). A better approach is to move the negative number if() check outside of the factorial function. The if (x < 0) check has its own purpose that is separate from calculating factorials: input validation.
In every recursive function, there exists a stopping condition (in your case its if(x<=1)) without which, the function would go to infinite recursion. You had not added that stopping condition. Following is the working updated program:
var x = prompt("Enter a number"); {
function fact(x) {
if (x < 0) {
return ("Enter a positive integer");
}
else if(x <=1){
return 1;
}
else {
return (x * fact(x-1))
}
}
}
var result = fact(x)
document.write("The factorial of " + x + " is " + result);
In addition to fixing the flawed algorithm, I recommend moving your prompt into its own function for separation of concerns.
I also like the idea of using a while statement for this as well as doing a parseInt on the input:
function fact(x) {
while (x > 1) {
return (x * fact(x-1));
}
return x;
}
function doFact() {
var x = parseInt(prompt("Enter a positive integer"));
if (x < 1) {
doFact();
} else {
var result = fact(x);
alert("The factorial of " + x + " is " + result);
}
}
doFact();

Division in javascript

function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3);
return (num3);
}
function division(num1, num2){
difference = parseFloat(subtraction());
var x;
while(difference > 0){
difference = num1-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
Hi! I wanted to do a division function but the catch is I will not use "/". This is what I got and so far this prints out "undefined" and if I stated x = 0 it will print out "0".
I fixed some problems with your code:
function division(num1, num2){
var difference = num1-num2; // difference is now a local variable
var x = 0; // x should be initialized
while(difference > 0){
difference = difference-num2; // difference should change, not always be num1-num2
x = x + 1;
}
console.log("Quotient" + x);
console.log("Remainder" + (difference+num2));
}
http://jsbin.com/UQIqejo/1/edit
You still have some problems with the algorithm itself, as num2 being less than or equal to 0 will result in an infinite loop, but i expect finding those problems is part of the fun.
EDIT: Smaller version of the same code:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
console.log('Quotient', x);
console.log('Remainder', a+b);
}
EDIT2: Correct division:
function divisionSmall(a,b) {
var x = 0;
while ((a-=b) > 0) x++;
return [x, a+b];
}
function divisionCorrect(a,b) {
var ans;
if (b === 0) return ['INF', 0];
if ((a > 0) && (b > 0)) {
return divisionSmall(a,b);
}
if ((a > 0) && (b < 0)) {
ans = divisionSmall(a,-b);
return [-ans[0], ans[1]];
}
if ((a < 0) && (b > 0)) {
ans = divisionSmall(-a,b);
return [-ans[0] - 1, b-ans[1]];
}
if ((a < 0) && (b < 0)) {
ans = divisionSmall(-a,-b);
return [ans[0] + 1, -b-ans[1]];
}
}
console.log(divisionCorrect(11,3)); // 3, 2
console.log(divisionCorrect(11,-3)); // -3, 2
console.log(divisionCorrect(-11,3)); // -4, 1
console.log(divisionCorrect(-11,-3)); // 4, 1
There is still the challenge of doing the logic without ifs :). Good luck.
If your doing numbers their is a simpler way to do this using recursion:
function divide(num,denom) {
if (num < denom) return 0;
return (1 + divide(num - denom, denom));
}
For negative numbers you would have to extend this to track if numbers were less than 0. Also, while concise and neat, this breaks down for large numerators and small denominators as the max call stack size will be exceeded.
I believe your issue is with your while loop. If the subtraction method returns a negative number it will not compute.
User Math.abs to get absolute value.
<script>
function division(num1, num2){
var difference = Math.abs(parseFloat(subtraction(num1, num2)));
var x = 0;
while(difference > 0){
difference = difference-num2;
x = x + 1;
}
document.writeln("Quotient" + x);
}
function subtraction(num1, num2){
var num3;
num3 = num1 - num2;
document.writeln("Difference "+ num3); return (num3);
}
</script>

Reverse decimal digits in javascript

How do I reverse the digits of a number using bitwise?
input:
x = 123;
output:
x = 321;
How Do this?
That's not inverting bits; that's reversing the order of decimal digits, which is completely different. Here's one way:
var x = 123;
var y = 0;
for(; x; x = Math.floor(x / 10)) {
y *= 10;
y += x % 10;
}
x = y;
If you actually want to invert bits, it's:
x = ~x;
As a function:
function reverse(n) {
for(var r = 0; n; n = Math.floor(n / 10)) {
r *= 10;
r += n % 10;
}
return r;
}
If you wanted to make a simple reversal:
var x = 123;
var y = x.toString();
var z = y.split("").reverse().join("");
var aa = Number(z);
document.write(aa);
http://jsfiddle.net/jasongennaro/gV39e/
Here is another way...
var reversed = num.toString().split('').reverse().join('');
jsFiddle.
If you wanted it again as a Number, use parseInt(reversed, 10). Keep in mind though, leading 0s are not significant in a decimal number, and you will lose them if you convert to Number.
you also use this function
function myfunction(a){
var x=a.toString();
var y= x.split("");
var z=y.reverse();
var result=z.join("");
return result;
}
myfunction(123);
Simple and quick solution: Let's assume that you want to reverse a number 4546. You will take the reminder from each division by 10 and append it to the result until the number is > 0. And simultaneously updating the num variable by dividing it by 10.
var x = '';
var num = 4546;
while(num>0){
x = x + (num%10);
num = parseInt(num/10);
}
console.log(x);
Reversing The Positive/ Negative Integer Number
function reverseInt(n) {
return parseInt(n.toString().split('').reverse().join()) * Math.sign(n)
}
If n is -5, then Math.sign(n)==> will return -1
If n is 5, then Math.sign(n)==> will return 1
Here are reversible array functions in JavaScript that handle integers or strings:
function reverse(array)
{
var left = null;
var right = null;
var length = array.length;
for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
{
var temporary = array[left];
array[left] = array[right];
array[right] = temporary;
}
return array;
}
function toDigitsArrayFromInteger(integer, isReverse)
{
var digits = [];
if (integer > 0)
{
var floor = window.Math.floor;
while (integer > 0)
{
digits.push(floor(integer % 10));
integer = floor(integer / 10);
}
// Array is populated in reverse order. Un-reverse it to make it normal.
if (!isReverse)
{
digits = reverse(digits);
}
}
else if (integer < 0)
{
digits = toDigitsArrayFromInteger(-integer, isReverse);
}
else if (integer === 0)
{
digits.push(0);
}
return digits;
}
function toDigitsArrayFromString(string, isReverse)
{
var digits = [];
string += ""; // Coerce to string.
var i = null;
var length = string.length;
for (i = 0; i < length; i += 1)
{
var integer = parseInt(string.charAt(i), 10);
if (isFinite(integer))
{
digits.push(integer);
}
}
if (isReverse)
{
digits = reverse(digits);
}
return digits;
}
Once you have the digits as an array, you can reverse the array easily to get the digits starting from the left or from the right.
The string function is more versatile because it can find any digit in a string, whereas the integer function is limited to integers.
Benchmarks:
http://jsperf.com/todigitsarray
The benchmarks between the two functions show that in Firefox 10 and Chrome 12, the string function is 30% to 60% faster than the integer function. In Opera 12, the integer function is slightly faster by about 10%.
//reverse integer
const revInt = (num)=>{
//turn into string
if(Math.sign(num)===1)
return parseInt(num.toString().split('').reverse().join(''));
else return -1*parseInt(num.toString().split('').reverse().join(''));
}
console.log(revInt(-501));
<html>
<script>
function reverseInt(n){
var r=0;
while(n!=0){
r*=10;
r+=n%10;
n=Math.floor(n/10);
}
return r;
}
</script>
</html>
try this
var n = 352;
function loop(n, r){
if(!n) return r;
r = (r ? r * 10 : 0) + n % 10;
return loop(Math.floor( n / 10), r);
}
console.log(loop(n));
OK, how about using and chaining these popular tricks in JavaScript in one-line function as below...
const reverseNum = num => +("" + ~~num.split("").reverse().join(""));
And call it like these:
reverseNum(123); //321
reverseNum(423.09); //324
reverseNum(23305.1); //50332
reverseNum(89112); //21198
reverseNum(568434.2389); //434865
This takes Number x as a parameter and returns the reversed number.
const reverse = (x) => Number(x.toString().split("").reverse().join(""));
Memory Usage: 35.3 MB, less than 100.00% of JavaScript online submissions for Reverse Integer on leetcode.com.
Runtime: 80 ms, faster than 61.48% of JavaScript online submissions for Reverse Integer.
Time complexity is O(log10(n)).
function reverse(x) {
let rev = 0;
const isNegative = Math.sign(x) === -1;
const isOverflow = n => n > 2**31;
x = Math.abs(x);
while (x) {
let pop = x % 10;
x = Math.floor(x / 10);
rev = rev * 10 + pop;
if (isOverflow(rev)) {
return 0;
}
}
return isNegative ? rev * -1 : rev;
}
The code block below should do the trick
<script type = "text/javascript">
var input;
input=window.prompt ("Please enter a number to be reversed.");
x=input.length;
while(x > 0)
{
x=x-1;
document.write(input[x]);
}
</script>

Categories

Resources