Why is there overflow in this for loop? - javascript

This loop loops all the way down to -30808 and I don't know why! I want it to count down to 1 or 0 from 100.
The stop condition is less than num or 1.
What's wrong with it?
Thanks
function first(num){
for (let i = num - 1; i > num || 1; i--){
let numFactorial = i;
console.log(numFactorial);
}
};
first(100);

you are initializing i as num -1 and starting to decrement, which means it is never going to be greater than num. If you are trying to continue the loop as long as i is greater than or equal to 1 then it should be as below.
for (let i = num - 1; i >= 1; i--)
Also anytime you are trying to compare a variable with two different conditions with || or && pls do as below and not i > num || 1 here you are comparing i with num but not with 1.
i > num || i >= 1

Related

Why always return "None" string, like my if statment was always false?

My second approach to learning JS.
Maybe someone will tell me why I always get "none".
Thank you for any help.
const reverseFactorial = (num) => {
for (let i = 1; num > 1; num = num / ++i) {
if (num === 1) return `${i}`
}
return 'None'
};
console.log(reverseFactorial(120))
check your if condition and for loop condition.num>i is your for loop condition so when i=1 in for loop it will immediately exit the for loop and not enters into the if condition so your if condition is never satisfied that's why you always get none.
so change your for loop condition to
num>=1;
Here's a working demo
Code Snippet
const reverseFactorial = (num) => {
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) return `${i}`
}
return 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Sure it is possible to perform this also with the ternary operator, you have to change the internal 'if' check with an assignment to a temporary variable (let's call it 'result') which will be holding the temporary result at each iteration until the num equals one (num === 1) condition is met or num is no longer greater than nor equal to one (num >= 1); at that point, the for loop will end and the result is returned with the associated 'reversefactorial' value or 'None' value:
const reverseFactorial = (num) => {
// this avoids exceptions if num < 1 as you always return a valid value
// by returning zero, the function is reporting an invalid num argument
result = 0
for (let i = 1; num >= 1; num = num / ++i) { // condition updated to "num >= 1"
result = (num === 1) ? `${i}` : 'None'
}
return result
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
You can also speed the loop by taking everything out like this:
const reverseFactorial = (num) => {
// take into account num < 1
if (num < 1) {
i = 0;
num = 1;
}
else i = 1;
for (;num >= 1; num = num / ++i) { // condition updated to "num >= 1"
if (num === 1) break;
}
return (num === 1) ? `${i}` : 'None'
};
console.log('reverseFactorial(120) gives: ', reverseFactorial(120))
Though, as you can see, it is now more cumbersome to take into account invalid num entries with the starting if to correctly set the initial value for i; anyway this function should be faster than the previous one, the more the higher num is as we are taking the assigment out of the loop.

undefined output in while loop w/array using Nth root equation javascript

I'm trying to write this code for an after effects expression that will move an object a calculated x distance over n number of frames. The movement over each frame is parabolic rather than linear, and so I'm using the nth root code to determine how much the object should move over each frame. I'm putting each of the nth roots into an array to access later when setting the positions for each move.
I'm still learning javascript mainly for AE, so please bear with me if there are things in here I don't fully understand. I think I understand, which is why I'm not sure I'm getting the undefined output for certain n values. Here's the code:
//get Nth root
function nthroot(x, n) {
ng = n % 2;
if ((ng == 1) || x < 0)
x = -x;
var r = Math.pow(x, 1 / n);
n = Math.pow(r, n);
if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
return ng ? -r : r;
}
distance=1515; //will be determined by another portion of the AE expression
frames=6; //will be set by expression control in AE
const myArray = [];
let i = 1;
while (i <= 6) {
myArray.push(nthroot(distance,i++));
}
console.log(myArray);
document.getElementById("demo2").innerHTML = myArray
I put it into a fiddle here. What am I doing wrong? Thanks in advance for any help!
Your "nthroot" function doesn't return values consisistently: if you look at the end of your function you can find this part:
if (Math.abs(x - n) < 1 && (x > 0 === n > 0))
return ng ? -r : r;
if you notice, you are returning a value only if the condition in the if statement is fullfilled, otherwise you are not returning any value.
In JavaScript, a function that doesn't return any value returns "undefined" instead.
In other words, when
Math.abs(x - n) < 1 && (x > 0 === n > 0)
is true, you are returning either "r" or "-r", but when the condition is false you aren't returning any value, so the function returns "undefined".
You have to handle the false case.

Creating a For loop to find sum of proper divisors

I have this problem for my CIS class: "Write a function named sumOfProperDivisors that accepts an integer n > 1, and returns the sum of the proper divisors of n.(A proper divisor is a positive divisor of a number, excluding the number itself. For example, 1, 2, and 3 are proper divisors of 6, but 6 itself is not.) Use a for loop, and use function expression syntax."
I don't even know where to start. This is all I have so far and I'm pretty sure it's completely wrong. PLEASE I NEED HELP
var sumOfProperDivisors = function(n > 1) {
let sum = 0;
for (var i = 1; i <= n; i++)
// we don't have to search all numbers from 2 to the integer part of n / 2,
// but from 2 to the integer part of the square root of n
// if n = 1000 we look for divisors in the interval [2, 31] and not in [2, 500]
const sumOfProperDivisors = n => {
const root = Math.sqrt(n);
let result = 1 + Number.isInteger(root) * root;
for (let k = 2; k < root; k++) {
if (n % k === 0) result += k + n / k;
}
return result;
}
console.log(sumOfProperDivisors(6));
console.log(sumOfProperDivisors(1000));
console.log(sumOfProperDivisors(1000000));
Welcome to Stack Overflow
Read about asking homework questions - How do I ask and answer homework questions?
Also, read about asking a good question - https://stackoverflow.com/help/how-to-ask
The answer:
You can do it like this:
loop over from i = 1 to i = n/2 because once it cannot be divisible by something greater and n/2 and n.
if the modulo (remainder) of n / i is zero then increment sum
return sum
function sumOfProperDivisors(n) {
let sum = 0;
for (var i = 1; i <= n/2; i++){
if (n % i == 0){
sum++;
}
}
return sum;
}
console.log(sumOfProperDivisors(6))
The laziest way to do this is loop through all the numbers before n, 1 to n-1
and check if the modulo of n with the number gives 0 that means n is divisible by that number then add that number to a variable "sum" each time the condition applies.
You can alter some details like looping from 1 to n/2 to remove unnecessary numbers.
When you define a function, what goes in the parenthesis is the name of the argument, possibly with a default argument value, but the > 1 syntax you're using is not valid.
So, instead of:
function (n>1) {...}
You would need to do something like:
function (n) {
if (n <= 1) {
// ... throw an error or something...
// or maybe you don't need to bother with this?
// it's not super clear to me from the assignment
}
The other thing I would point you to in order to answer your question is the modulo operator, which is the percent sign (%) in javascript. That operator will return the remainder of a division operator, so if you want to check if a number is divisible by another number, you can check if the remainder is 0 in this way...
if (3 % 2 === 0) { console.log('3 is divisible by 2')}
if (4 % 2 === 0) { console.log('4 is divisible by 2')}
if (5 % 2 === 0) { console.log('5 is divisible by 2')}
One final note: it's nice to write a bunch of tests for yourself to see how your function works and see if you understand it. So if I got this problem as homework, the first thing I might do is write a bunch of statements to test out my answer and see how they work...
For example:
console.log('sumOfProperDivisors(4) should be 3... and it is ',sumOfProperDivisors(4))
console.log('sumOfProperDivisors(5) should be 1... and it is ',sumOfProperDivisors(5))
console.log('sumOfProperDivisors(6) should be 6... and it is ',sumOfProperDivisors(6))
console.log('sumOfProperDivisors(8) should be 7... and it is ',sumOfProperDivisors(8))
function findProperDivisor(num) {
if(num<0) return
let sum = 0;
for (let i = 0; i < Math.floor(num / 2); i++) {
if (num % i === 0) {
sum += i;
}
}
return sum
}

Why do both these two solutions for printing all numbers divisible by 3 AND 5 between 5 and 50 work?

This was my solution to the problem:
var count = 5;
while (count <= 50) {
if ((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This was my the instructors solution:
var count = 5;
while (count <= 50) {
if (count % 3 === 0 && count % 5 === 0) {
console.log(count);
}
count++;
}
Both of these solutions gave the proper answer, but I question why || worked in my problem, rather than &&, I tried both. && means both need to be true for it to properly run, right? So wouldn't that have been the proper use?
var count = 5;
while(count <= 50) {
console.log(`count = ${count} | (count % 3 || count % 5) = ${(count % 3 || count % 5)}`);
if((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This happens because in all cases where count % 3 === 0 and count % 5 does not, the number takes precedence in the or (||) statement since it's "truthy".
eg.
count = 6, 0 || 1 // 1, since 0 is "falsy"
count = 8, 2 || 3 // 2
count = 15, 0 || 0 // 0
Therefore, it seems you stumbled on the correct solution.
It is a javascript peculiarity you encounter. If count % 3 is 0 it is considered "falsy" and the other calculation will be used. So if either modulus has a remains, that value is used in the final test against 0.
So while both works, your teachers code is more readable; thus better.
The following code
(count % 3 || count % 5) === 0
evaluates first the % operations and then the or to end with ===. If both modulo operations return 0, the or condition also evaluates as 0, that compared with 0 equals true and print the numbers. Otherwise, if any of the modulo values isn't 0, the or operation will result in these numbers, hence it won't be printed.
This is because Javascript evaluates numeric values as boolean being 0 False, and any other value True.
In your case it's a question of parenthesis
1st case of || with parenthesis like this ((count % 3 || count % 5) === 0) it like you say count has to be % by 3 and 5 so it's like &&
2nd case (count % 3 === 0 && count % 5 === 0) you've changed the parenthesis to regroup all
with && in the middle
so as i said it's question of parenthesis that makes both solution give the same result
Every value except 0 is evaluated as true. If there is a number divisible by 3 AND 5 both, then 0 || 0 is 0, which makes your if condition to run. If there is a number that is only divisible by 3 OR 5, lets say 10, then 10%3 is equal to 10 and 10%5 is equal 0. 10 || 0 will be evaluated as true (non-zero). Since non-zero value is not equal to 0 therefore if condition will not execute.
I am not sure but your instructors expression can be said as created from your expression by using Demorgans law.
The second solution is more useful than the first.
Because always "%" operator is computational, not logical

What is the functionality of the while loop inside the if statement? JavaScript

Below is a function that returns the prime factors of a given number in JavaScript.
I did not write the function but have been studying it to extend my programming knowledge.
My questions are about the while loop that is inside the following if statement.
if(num % x){
x = 3;
while((num % x) && ((x = x+2) < root));
}
Questions
What is the purpose of a while loop if there is no code after it?
What is happening when the while loop evaluates true?
What is happening when the while loop evaluates false?
Here is the function in it's entirety.
function getPrimeFactors(num){
num = Math.floor(num);
var root = 0;
var factors = [];
var doLoop = 1 < num;
var x = 0;
while(doLoop){
root = Math.sqrt(num);
x = 2;
if(num % x){
x = 3;
while((num % x) && ((x = x+2) < root));
}
if(x > root){
x = num;
}else{
x = x;
}
factors.push(x);
doLoop = (x != num);
num = num/x;
}
return factors;
}
Thanks for the help!!!
It is really doing something like this:
if(num % x){
x = 3;
while(num % x){
x = x + 2;
if(x < root)
continue;
else
break;
}
}
Except, two is added to x right in the conditional, so there is no need for a body. The loop will execute until x < root or num % x fails to be true. The body just doesn't have any instructions in it.
Its very similar to what happens when you execute a for loop
for(int i=0; i < n; i++)
;
See there are no instructions in the for-loop body, but the loop will still add one to i until i >= n.
Note the x = x+2 in the while statement. It adds 2 to the value of x repeatedly until the while clause evaluates true.
So a while loop without a body blocks execution until it's clause becomes true. This is only a good idea if you you are mutating a variable in the clause as part of the condition. Otherwise you may end up in an infinite loop.
This code says, in effect, that if x is not evenly divisible by 3, then add 2 to x and continue if the resulting value is less than root. The loop terminates as soon as one of these conditions is no longer true, but, meanwhile, x has been updated along the way.
Note that x = x + 2 evaluates to the assignment's left operand.
The while statement there does change the value of the x variable. It could be rewritten as something like the following:
if (num % x) {
x = 3;
if (num % x){
do {
x = x + 2;
} while (num % x && x < root);
}
}
There is actually one thing happening in the loop:
V
while((num % x) && ((x = x+2) < root));
x = x + 2 is an assignment, you can see it is not a == or === operator but a =.
(x = x + 2) < root means increment x by 2, and then compare it to root.
Using an assignment in the condition part of a while or if statement is generally not recommended, because it makes the code less readable.
The value of x is incremented (by 2) until it is equal to or greater than the value of root
There's an assignment in the while condition/loop. It's evaluated while the loop is running so the value of "x" gets updated every cycle until no longer < root ( besides/and: && num % x < root).
Very clever but I hope this is not an introduction text/book/post to programming.
It seems like your hang-up you're having is with the fact that there's no body in the while statement. Understand that a loop body is optional and that it it behaves in the same way as a loop that does have a body.
Basically the while loop will repeatedly check the condition over and over. Yes, this can result in an infinite loop if coded incorrectly. In this case, 'x' will be incremented by 2 until it reaches or exceeds the value of 'root'.
credit to #Teemu for "reaches or"

Categories

Resources