I've just started to learn JS and I'm having a bit of trouble understanding the basics behind the 'for' loop.
Example:
for (var number = 3; number % 7 == 0; number++)
Why doesn't it make sense? Why do I have to write it down like that:
for (var number = 3; ; number++) {
if (number % 7 == 0)
break;
}
Thank you for help!
You've inverted the condition. The middle part of a for loop tells you what must be true for the loop to continue. Your second version uses the same condition to decide when to stop.
for (A; B; C) { ... }
can be (mostly) rewritten as
A;
while (B) {
...
C;
}
(The difference is that continue in a for loop will still execute the C part.)
Initially your number is 3. Then we do the equivalent of while (number % 7 == 0) { ... }, but that condition fails (3 % 7 is 3, not 0), so the loop never runs.
You probably wanted
for (var number = 3; number % 7 != 0; number++)
Related
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
}
The code here check for prime numbers from 2 to n:
<script>
function showPrimes(n) {
for (let i = 2; i < n; i++) {
if (!isPrime(i)) continue;
alert(i); // a prime
}
}
function isPrime(n) {
for (let i = 2; i < n; i++) {
if ( n % i == 0) return false;
}
return true;
}
</script>
But I don't understand why it works for number 2 and return false when both n and i equal to 2 while it doesn't happen with other prime numbers. I am new to javascript(and programming in general) and from what I understood this code take the i from the first iteration in the first loop(on the "showPrimes" function) and put it on "isPrime" function as a parameter and in that function it becomes the "n" in the 'if' condition and it checks if there is a remainder when it gets divided by the i from the loop of "isPrime" so (n % i == 0) should be (2 % 2 == 0) in the first iteration, Is that right? if so why does it works just like it work for other prime numbers which clearly become false unlike (2 % 2 == 0) which is true...
What I am missing here?. Sorry if this is an obvious/stupid question, it is the first time I am learning anything related to programming.
function isPrime(n) {
for (let i = 2; i < n; i++) {
When n=2; i=2; The above loop will not be entered.
This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 7 years ago.
If I do a simple loop with a while, it is evaluating my ++ operator after the first loop, does this mean that my while operator makes a small scope saving my i and after it finishes evaluating it applies the ++ operator on it? Why does this happen with this operator and also happens on the -- but not with lets say a simple sum i + 1?
var i = 0;
while(i++ < 1) { console.log(i) }
My output is
1
var i = 1;
while(i-- > 1) { console.log(i) }
My output is
0
var i = 0;
while(i + 1 < 1) { console.log(i) }
My output is
undefined
i++ first evaluates and then increments.
++i first increments and then evaluates whatever expression it is in.
var i = 0;
while(i++ < 1) { console.log(i) }
First you get 0 < 1, it gets incremented, it enters the loop and printed as 1. console.log() runs once. The next iteration would compare 1 < 1 which returns false. Do note that i is 2 in the end, because this second comparison increments it again.
var i = 1;
while(i-- > 1) { console.log(i) }
Here evaluates to 1 > 1. You will not get a console.log, but it will be 0 because it gets decremented after being evaluated.
var i = 0;
while(i + 1 < 1) { console.log(i) }
Here the incrementation is done instantly, so you get 1 < 1 which doesn't evaluate as true, thus you don't enter the loop. i should be 0 in the end because it isn't modified.
For the first statement, the order of execution is:
is i (currently 0) < 1 ? if so, increment i and enter loop, else increment i.
output i (1)
The second is largely the same deal but your final statement is quite clearly never going to execute. we take zero, add 1 to it and then compare to 1. Thus your statement is the equivalent of while (1 < 1) which is clearly never true.
I think you're confusing i++ and ++i (this isn't because of the loop):
i++ evaluates to i and then increments i
++i increments i and then evaluates to i
Some examples:
var i = 0;
console.log(i++); // ⇒ 0
console.log(i); // ⇒ 1
i = 0;
console.log(++i); // ⇒ 1
console.log(i); // ⇒ 1
i = 1;
console.log(i++); // ⇒ 1
console.log(i); // ⇒ 2
You can find more information here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()
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"
I am trying to write a function that returns the PrimeNumber. for testing purposes i am just doing a console.log for stages of this function, to try and understand it better.
so this line(line:18) in my total function will just return i; as opposed to do a console.log
So Basically, 30 will be passed to the function and the function will return every prime number <=30.
It is based on this from wiki:
This routine consists of dividing n by each integer m that is greater than 1
and less than or equal to the square root of n.
If the result of any of these divisions is an integer,
then n is not a prime, otherwise it is a prime.
(Question here: 25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime as 12.5 is not an integer Or am I mising something here???)
there is also the problem of duplication: 13 is printed twice because 13/2 and 13/3 is executed. Question here: I would like to fix this duplication also?
function isInt(n) {
return n % 1 === 0;
}
var test = 25
console.log(Math.sqrt(test));
function prime(n) {
for(var i = 1; i <= n; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump
to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "/" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i/j); //because the sqrt of 9 = 3 =>
for j= 2 and j=3
if(isInt(i/j)) {}
else{console.log("----" + i + "is Prime");}
}
}
}
};
prime(test);
Another example here using aslightly different method: but again I have the same problem as the above 25 and duplication
var test = 25
console.log(Math.sqrt(test));
for(var i = 1; i <= test; i++)
{ if(i%2 !==0 && i%3 !==0){ // if i/2 does not have a remainder it might be a prime so go to next line else jump to next number and i%3 the same
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++){
console.log(i + "%" + j); //print j//it prints 9 twice and 10 twice
console.log("==" + i%j); //because the sqrt of 9 = 3 => for j= 2 and j=3
if(i%j !==0) {
console.log("----" + i + "is Prime");
}
}
}
}
[EDIT]Thank you all very much for pointing out my flaws/mistakes
here is my working example. Thank you all again!!
function isInt(n) {
return n % 1 === 0;
}
var test = 100
console.log(Math.sqrt(test));
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
var bool = true;
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
//console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
} else {bool = false;}
}
if(bool) {console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");}
}
}
prime(test);
25/Math.sqrt(25) = 0, therefore NotPrime
BUT 25/2=12.5, 25/3=8.3333 25/4=6.25 => IsPrime
No. Only because it neither is divisible by 2, 3, and 4, it does not mean that 25 is a prime number. It must be divisible by nothing (except 1 and itself) - but 25 is divisible by 5 as you noticed. You will have to check against that as well.
13 is printed twice because 13/2 and 13/3 is executed.
Question here: I would like to fix this duplication also?
Your logic is flawed. As above, just because a number is not divisible by an other number that does not mean it was prime - but your code prints results based on that condition. Instead, is has to be not divisible by all other numbers.
You just have an extra condition that nothing that is divisible by 2 or 3 enters the loop, but everything that is divisible by 5, 7, 11 etc (and not divisible by 2 or 3) is yielded. 25 is just the first number to occur in that series, the next ones will be 35 and 49.
Actually you're already testing 2 and 3 in the loop from 2 to a already, so you should just omit that condition. You would've noticed your actual problem much faster then if you had tried:
function prime(n) {
for (var i = 1; i <= n; i++) {
var a = Math.floor(Math.sqrt(i));
for(j = 2; j<=a; j++) {
if(!isInt(i/j)) {
console.log(i+"/"+j+"=="+i/j+", therefore "+i+" is Prime");
}
}
}
}
prime(25);
The logic should be: Test all divisors from 2 to sqrt(i), and if i is divisible by any of them you know that it's not a prime. Only if it has passed the loop with none of them being a factor of i, you know in the end that it's a prime. I'll leave that as an exercise to you :-)