Why does this program not print anything in the page? - javascript

//This program calculates how many times a number is divisible by 2.
//This is the number and the amount of times its been split into 2.
let Num=64
let divisible=0
//This is the ternary operator, it basically asks a question.
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
Num/=2;
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
num/=2
Num % 2 === 0 ?
divisible=divisible++ : document.write(divisible);
//Once the statement evaluates to false it writes the amount of times the number has been divided
by 2 into the document.

You could try it with a loop.
let num=64;
let divisible=0;
while(num % 2 === 0) {
num /= 2;
divisible++;
}
console.log(divisible);
document.write(divisible);

There are several issues with this code. Some of the comments have pointed out the looping concerns. However, one that stands out that won't be addressed with a loop is your misuse of the post-fix increment operator, ++. This operator returns the value and then increments the value, so divisible = divisible++ will result in divisible remaining unchanged. Based on your intent, all you need to do is divisible++.
Try the following:
while(true){
if(Num % 2 === 0){
divisible++;
Num /=2;
}
else{
document.write(divisible);
break;
}
}

Here as per example given for 64 and no looping is provided , it will never go to
document.write(divisible) statement in 3 step provided above . That's why nothing getting printed .
Moreover , divisible=divisible++ doesn't make any sense . Here , since it is postfix operartor , first value will be assigned then it will be incremented so value of divisible will be 0 only .
Num % 2 === 0 ?divisible++ : document.write(divisible);
And , as per my understanding document.write accepts string parameter but here divisible is of number type .

Related

Prime Number Check (JavaScript) [duplicate]

This question already has answers here:
Check Number prime in JavaScript
(47 answers)
Closed 2 years ago.
I have written the below code to check if a number is prime, and it works correctly. But to my amazement when it pass 25 as a value, it returns "true" instead of "false" because 25 is not a prime number.
So I decided to share. Please, what I am doing wrong here?
function isPrime(number) {
return number % 2 !== 0 && number % 3 !== 0 ? true : false;
}
isPrime(4) returns false;
isPrime(23) returns true;
isPrime(25) returns true;
"(Here is where I got alarmed. 25 Should return false too)
Your condition is very minimal. What if the number is not divisible by 2 or 3 but divisible by 5 or 7? Besides how come isPrime(23) returns false is okay? 23 is a prime as well it should return true. What you need to do is iterate through all the number from n-1 to 2(here n is the number you are checking) and check if any of the number divides n without a remainder. You can do the following,
function isPrime(number) {
let isPrimeNum = true;
for(let i = number-1; i>=2; i--) {
if(number%i === 0) isPrimeNum = false;
}
return isPrimeNum;
}
console.log(isPrime(23));
console.log(isPrime(25));
There is a lot of way you can optimize the above solution. I kept it as a challenge for you to find out and do by yourself. You can start from here.
Your code only checks if the input is divisible by 2 or 3. However, a prime number (by definition) is a number that's only divisible by 1 and itself.
Therefore, you have to check every number less than or equal to sqrt(n). (It's enough to scan this area, as if there's a divisor greater than that, it must have a pair that falls in that range.
The loop iterates upwards, so it can early-return, if the number is divisible by a small prime.
function isPrime(number){
if(number <= 1 || number !== Math.floor(number))
return false
const sqrtNumber = Math.sqrt(number)
for(let n = 2; n <= sqrtNumber; n++)
if(!(number % n))
return false
return true
}
console.log(isPrime(-42)) //false
console.log(isPrime(1)) //false
console.log(isPrime(3.14)) //false
console.log(isPrime(4)) //false
console.log(isPrime(23)) //true
console.log(isPrime(25)) //false

Explain the Javascript code, pad to left or rightside of string

I am learning Javascript and trying to do some challenges on codewar. I have the code for a challenge and I am trying to understand the logic.
The code snippet of interest is the function padIt, which accepts 2 parameters:
str - a string we need to pad with "*" at the left or rightside
n - a number representing how many times we will pad the string.
My question is, why do they use n-- and not n++?
function padIt(str, n) {
while(n>0) {
if(n%2 === 0) {
str = str + "*";
}
else{
str = "*" + str;
}
n --;
}
}
if you use n++ the while loop will never end since it is checking if n is larger than 0
imagine n is 3: n will be 4,5,6,7,8 then it is a infinite while loop
instead n represent how many times to pad the string so if you want to add 3 * n will go down from 3 to 2 to 1 and the while loop will end
Why n-- and not n++?
First of all notice the condition of while loop n>0. It means keep executing the while block. Means keep padding the string until n is greater than 0. Initially n is always greater than 1. So we need to decrease is in order to end the while loop.
If we use n++ instead of n-- the code will create infinite loop

Trouble with recursive functions

Can anyone explain this to me? I'm having trouble wrapping my head around this concept of having function within a function.
function factorialize(num) {
if (num === 0) {
return 1;
}
return num * factorialize(num-1);
}
factorialize(10);
This is not a loop right? Why does the function call itself continuously? How does it know when to stop? Wouldn't it just continue to factorialize negative numbers to infinity?
Appreciate the help and guidance as always.
This is not a loop right?
Nope, it is not. It is a recursive function, a function that calls itself until a certain condition is met. In this case, is when num is equals to 0.
Why does the function call itself continuously?
Because the function is called in the return value of this function. It will continue calling the function itself, until num equals 0. In which case the function will exit and return 1.
How does it know when to stop?
The condition if (num === 0). The variable num gets subtracted if num isn't equal to 0 as stated in the code return num * factorialize(num-1);. Notice that the function returns fresh function call but with the parameter num - 1. When num becomes 0. The function returns 1.
Wouldn't it just continue to factorialize negative numbers to
infinity?
Because we have this if (num === 0) condition. So the num parameter decreases each time the code return num * factorialize(num-1); gets called, and eventually the above condition gets fulfilled and the function exits.
We can break it down step by step:
factorialize(10) gets called.
num is not 10, so return num * factorialize(num - 1). In this case num is 10 and num - 1 is 9, so we are actually returning the following: 10 * factorialize(10 - 1).
factorialize(9) gets called, then repeat step (1) and (2) until you get factorialize(0).
When you reach factorialize(0), it will return 1. So the whole function effectively returns 10 * 9 * 8 * ... 1 * 1.
Makes sense?
Recursion is a technique for iterating over an operation by having a function call itself repeatedly until it arrives at a result. You can read about it here
Lets visualize:
factorialize(10)
10*factorialize(9)
9*factorialize(8)
8*factorialize(7)
7 *factorialize(6)
6 *factorialize(5)
5 *factorialize(4)
4 *factorialize(3)
3 *factorialize(2)
2 *factorialize(1)
1 *factorialize(0)
1 (if num==0 return 1)
1
2
6
24
120
720
5040
40320
362880
3628800
Hope this helps!
Each time the function "factorialize" runs your argument "num" get decremented by
1. So num will run from 10 to 1 and when 1 is returned it will reach its terminal case 0. It is only terminal because of your "if" clause ( your base case ) when num === 0, you return 1, and your recursive "factorizlize" is never reached, so it is never executed.
I am not really good with analogies. However, If it still doesn't make sense let me know.
Every iterative problem can be solved by using recursion. try to look at this code
var start = 1;
var end = 10;
var increment = 1;
document.write("loop output: ")
for(var num = start; num <= end; num = num + increment){
document.write(num);
document.write(" ");
}
document.write("\n function output:\n")
function iteration(num) {
//stop condition statement
if (num > end) {
return 1;
}
// inside code block
document.write(num);
document.write(" ");
//incremention
iteration(num+increment);
}
iteration(start);
It uses internal functional frame stack for recursion purpose. for more about recursion look here . little practice is need to understand this concept.Hope make sense. Happy Coding !

& 1 JavaScript. How does it work? Clever or good? [duplicate]

This question already has answers here:
Is there a & logical operator in Javascript
(8 answers)
Closed 6 years ago.
I'm looking over the solutions for a CodeWars problem (IQ Test) in which you're given a string of numbers and all the numbers but 1 are either even or odd. You need to return the index plus 1 of the position of the number that's not like the rest of the numbers.
I'm confused about the line that says & 1 in the solution posted below. The code doesn't work w/ && or w/ the & 1 taken away.
function iqTest(numbers){
numbers = numbers.split(' ')
var evens = []
var odds = []
for (var i = 0; i < numbers.length; i++) {
if (numbers[i] & 1) { //PLEASE EXPLAIN THIS LINE!
odds.push(i + 1)
} else {
evens.push(i + 1)
}
}
return evens.length === 1 ? evens[0] : odds[0]
}
Also, would you consider using & 1 to be best practice or is it just "clever" code?
The single & is a 'bitwise' operator. This specific operator (&) is the bitwise AND operator - which returns a one in each bit position for which the corresponding bits of both operands are ones.
The way it's being used here is to test if numbers[i] is an even or odd number. As i loops from 0 to numbers.length, for the first iteration the if statement evaluates 0 & 1 which evaluates to 0, or false. On the next iteration of the loop, the statement will be 1 & 1, which evaluates to 1, or true.
The result - when numbers[i] & 1 evaluates to 0, or false, then numbers[i] is pushed to the odd array. If numbers[i] & 1 evaluates to 1, or true, then numbers[i] is pushed to the even array.
An alternative to the & operator to test for even and odd is to use the modulo operator. numbers[i] % 2 results in the same output. That is, 1 % 2 results in 1, or true as will any odd number, because an odd number divided by 2 results in a remainder of 1. And any even number, like 2 % 2 results in 0 or false because an even number divided by 2 results in a remainder of 0.
As for your second question, is it 'clever or good?'. It's definitely clever. Whether it's good depends on who you ask and what your goal is. Many would say its less logical and harder to read than using num % 2.
Binary number is 0 and 1 and each of them is called bit.
Single & is add operation and it works bitwise.
like
1 = 01
2 = 10
3 = 11
4 = 100
You can see that every last bit of odd number is 1 and even number is 0.
In add operation
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
So only odd number will return 1 and even number will return 0 and in programming only 0 consider falsy.
If we wanna to check 5 is a odd or even
5 = 101
and perform and(&) operation with 1
101
& 001
-----
001
and value of binary 001 is 1 in 10 base number
So it'll perform easy odd even process.

Can you explain how this Factorial function works?

I understand that "a" solution is:
function Factorial(number)
{
if(number == 0 || number == 1){
return 1;
}
return number * Factorial(number -1);
}
I want to understand what exactly is going on. I understand what is going on all the way to the last part when number == 1.
If we were to take a simple example of say 3!
3 is not equal to 0 or 1 so we return 3 * Factorial(2)
2 is not equal to 0 or 1 so we return 2 * Factorial(1)
1 is equal to 1 so we return 1
How do we know when to stop? Is it the fact that we return 1 that tells the function to stop?
If that is the case, why does the function not stop when we first return 3 * Factorial(2)? Is it because it's returning a function so that it must continue until it no longer returns a function?
Thank you
I think you have to understand the logic of factorial.
So factorial is just products, indicated by an exclamation mark ie, if you write
0! = 1
1! = 1
2! = 2*1
3! = 3*2*1
4! = 4*3*2*1
5! = 5*4*3*2*1
Hope you find the pattern, so you can write the above factorials as:
0! = 1
1! = 1
2! = 2*1!
3! = 3*2!
4! = 4*3!
5! = 5*4!
So in your function you are using the similar logic.
Now in your function
if(number == 0 || number == 1)
{
return 1;
}
The above logic is to cover the first two cases i.e, 0! and 1! And
return number * Factorial(number -1);
is for the rest of the numbers.
So you are using the recursive technique of solving the factorial problem.
To understand recursion, lets take a number say 5 i.e., we want find the value of 5!.
Then first your function will check
if(number == 0 || number == 1)
which is not satisfied, then it moves to the next line ie,
return number * Factorial(number -1);
which gives
5*Factorial(5-1) which is equal to 5*Factorial(4)
Now on subsequent calls to your Factorial function it will return the value like below:
5*(4*Factorial(4-1)) which is equal to 5*(4*Factorial(3))
5*(4*(3*Factorial(3-1)) which is equal to 5*(4*(3*Factorial(2)))
5*(4*(3*(2*Factorial(2-1)))) which is equal to 5*(4*(3*(2*Factorial(1))))
Now when it returns factorial(1) then your condition
if(number == 0 || number == 1)
is satisfied and hence you get the result as:
5*4*3*2*1 = 120
On a side note:
Beware that factrial is used only for positive integers.
Recursion relies on what is called a base case:
if(number == 0 || number == 1){
return 1;
}
That if statement is called your base case. The base case defines when the recursion should stop. Note how you are returning 1 not returning the result of a call to the function again such as Factorial(number -1)
If the conditions for your base case are not met (i.e. if number is NOT 1 or 0) then you proceed to call the function again with number * Factorial(number - 1)
If that is the case, why does the function not stop when we first return 3 * Factorial(2)?
Your simple example of 3! can be elaborated like this :
return 3 * Factorial(2)
will then be replaced by
return 3 * (2 * Factorial(1))
which then will be replaced by
return 3 * (2 * 1) // = 6 Hence 6 is returned at last and recursion ends.
How do we know when to stop?
When all your Factorial(value) is replaced by a returned value we stop.
Is it the fact that we return 1 that tells the function to stop?
In a way, yes. Because it is the last returned value.
It is called recursion.
This function is called like this
var result = Factorial(3);
in Factorial function
First time
return 3*Factorial(2);
Now here return statement doesnt get executed insted Factorial is called again..
so second time
return 2*Factorial(1);
again in Factorial(1)
Third time
return 1;
So go to second
return 2*1;
Next to first
return 3*(2*1);
Finally
var result = 3*2*1 = 6.
The function is recursing (calling itself) - and taking one from "number" each time.
Eventually (as long as its a positive integer you call it with, otherwise you'll probably get an infinite loop) you'll always hit the condition (number == 1) so instead of recursing further, it'll return 1 rather than call the function again.
Then, once you have hit the bottom (1), it'll start to run the function and work back up the other way along the function call stack, using the previous result each time:
1 = 1
(2*1) = 2
(3*2) = 6
(4*6) = 24
etc
So the final return statement from the function will return the required result

Categories

Resources