How; The most difficult question of your life [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
function factorial2(n) {
for (product = 1; n > product; product++) {
product *= n;
}
return product;
}
factorial2(4);
return is receiving 5, why?
factorial2(4);

It returns 5 on first iteration if you pass 4 to it. In general it returns n + 1 for any n > 1.
Following the code path, it can be unrolled into
product = 1
n > product // true, loop
product *= n // so product is n
product++ // end of loop, product is n+1
n > product // false, exit loop
return product
If n === 1, the first check is false so it returns just 1.

If you want an iterative factorial function, you want to separate your step (step) variable and your accumulator (product).
function factorialIterative(n) {
let product = 1;
for (let step = 1; step <= n; step++) {
product *= step;
}
return product;
}
new Array(10).fill(0).forEach((v, i) =>
console.log(`${i} => ${factorialIterative(i)}`));
.as-console-wrapper { top: 0; max-height: 100% !important; }

Related

Debugging small javascript with exponents [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
n = 1;
while (n < 1024) {
alert(Math.pow(n, 2));
n = n + 2;
}
How can I make this display the powers of 2 from 2^0 to 2^10 inclusive i.e. (1-1024) and end once it reaches 1024 in Javascript
I would do something like this:
for(let n = 0; n <= 10; n++) {
console.log(2 ** n)
}
This logs the answer of each loop iteration. As Pointy suggested in the comment, we have to make the n value iterate from 1 to 10, since that is the variable that generates the output, whereas the 1024 is simply the output that comes from the power values. You could also use Math.pow as follows:
for(let n = 0; n <= 10; n++) {
console.log(Math.pow(2, n))
}
Implementing Secan's suggestion, here is a function which will take any number as a parameter:
function foo(x, exp) {
for(let i = 0; i <= exp; i++) {
console.log(x ** i)
}
}
So to apply this to the original answer, we would call it like this:
foo(2, 10)
Sorry for the ambuiguity with my original question. I've figured it out-
n=0;
while (n <= 10) {
alert(Math.pow(2, n));
n = n + 1;
}
Setting n=0, n<=10 in while and changing n + 1 instead of 2 resolved my issue. Thanks for your responses!

How i can get array from loop for? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hello everybody can you help me get percent with steps?enter image description here
function getPlan(currentProduction, months, percent) {
// write code here
let sum = 0;
for(let i = 0; i < months; i++){
let workCalculate = currentProduction * percent / 100;
sum *= workCalculate;
}
return Math.floor(sum);
}
example:
getPlan(1000, 6, 30) === [1300, 1690, 2197, 2856, 3712, 4825]
getPlan(500, 3, 50) === [750, 1125, 1687]
Simply push each iteration to an array and return that array.
function getPlan(currentProduction, months, percent) {
// write code here
// starting at currentProduction
let sum = currentProduction;
// output
let output = [];
for(let i = 0; i < months; i++){
// progressive from sum and not from currentProduction
let workCalculate = sum * percent / 100;
sum += Math.floor(workCalculate);
output.push(sum)
};
return output
};
console.log(getPlan(1000, 6, 30))
console.log(getPlan(500, 3, 50))
Currently your method returns a number, not an array. What do you need exactly? Do you need it to return an array or you just want to see the intermediate values of the calculation done inside the loop?
In the first case, create an empty array and add the values you want to it in each step of the loop:
function getPlan(currentProduction, months, percent) {
// write code here
let sum = 0;
var result= [];
for(let i = 0; i < months; i++){
let workCalculate = currentProduction * percent / 100;
sum *= workCalculate;
result.push(sum);
}
return result;
}
In the second case, you have 2 options:
Add a console.log so the values are printed to the console.
Add a breaking point so the code stops at it and you can see the values of the variables and go step by step through the execution of the program.
This is a bit vague because your need is unclear, hope it helps though!
function getPlan(currentProduction, months, percent) {
var plan=[];
var workCalculate=currentProduction;
for(var i=0; i<months; i++) {
workCalculate*=(1+percent/100);
plan.push(Math.floor(workCalculate));
}
return plan;
}
console.log(getPlan(1000, 6, 30));
console.log(getPlan(500, 3, 50));
.as-console-wrapper { max-height: 100% !important; top: 0; }

JavaScript Function. Can someone help or explain why it logs 120? I see 20 based on my analysis [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I would like to sum up all the elements inside the array covertedValue. Why I am getting a Nan result? whats wrong with the recursive function I have written?
function findOutlier(integers){
var covertedValue = integers.map(x => x % 2);
var total = 0;
for (i=0 ; i<covertedValue.length ; i++){
total = total + covertedValue[0] + findOutlier(integers.splice(1));
}
console.log(total);
}
findOutlier([0, 1, 2]);
because this line create a function and a private alias to itself
var factorial =
// create a variable named factorial in global scope
// it contains the function fac
function fac(n) {
// fac is a function available only in the factorial var context
return n < 2 ? // if n < 2
1 : // return 1
n * fac(n - 1); // else return n * fac(n - 1)
};
console.log(factorial(5));
// calls factorial(5) which is 5*fac(4) which is 5*(4*fac(3)) ...
note that the fac function is not available outside of itself
var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); };
console.log(fac(5));
This way of coding where a function call itself is called recursive programming it can be hard to grasp at first but can be VERY powerful in some situations
recurcive programming can easily be used when the result of func(n) depend directly on the result of func(n+x)
the cond ? then : else structure is called ternary operator, it's a way to make if in one line, can become messy very quick
as you noted in a comment : recursion can be replaced by a loop (it can be hard to do it sometime)
here's a more beginner way to write it
function factorial(n) {
if(n < 2) {
return 1
} else {
let fac = 1;
for(var i = n; i > 0; i--) {
fac = fac * i
// here fac takes the value of the precedent iteration
}
// this whole loop is the same as i*fac(i-1) in the recurcive way
return fac
}
};
console.log(factorial(5));

Why this solution can't use a for-loop? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I was donig Intersection of Two Arrays II in leetcode.
I found solution in it and one thing that i don't understand is
Why this solution can't use for loop?
if i changed this line of code
while(p1 < nums1.length && p2 < nums2.length)
into
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
the output will changed to only [2] not [2,2]
Why is that happened?
Request:
Given two arrays, write a function to compute their intersection.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Here is the JS code:
var intersect = function(nums1, nums2) {
nums1.sort(cm);
nums2.sort(cm);
var p1 =0
var p2 =0
var res = [];
while(p1 < nums1.length && p2 < nums2.length) {
if(nums1[p1] === nums2[p2]) {
res.push(nums1[p1]);
p1++;
p2++;
} else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
}
return res;
};
var cm = function(a, b) {
return a - b;
}
console.log(intersect([1,2,2,1], [2,2]))
Consider the following for loop
for(let p1=0,let p2=0;p1 < nums1.length && p2 < nums2.length;p1++;p2++)
In this p1 and p2 always get increased in every loop. But in you you original code. There are increased conditionally
Why for loop returns `[2]`:
When you increase p1 and p2 initially setting them to 0. So it means
in every loop the p1=p2. And hence it will compare the values on same indexes.
In the following two arrays.
[1,2,2,1]
[2,2]
Only the second 2 ([1,2,2,1] [2,2]) will be matched because both have same index 1.
else if(nums1[p1] > nums2[p2]) {
p2++;
} else {
p1++;
}
You can also do that using filter() and includes()
const intersect = (num1,num2) => num1.filter(x => num2.includes(x))
console.log(intersect([1,2,2,1],[2,2]))

Multiply two numbers without using multiplication [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have a test, where I needed to code for multiplying two numbers without using multiplication,
the code is as follows,
function multiply(num,toNum){
var product = 0;
for(var i = 1; i <= toNum; i++){
product += num;
}
return product;
}
console.log(multiply(2,5));
The output is
rahul#rahul:~/myPractise/Algo$ node MultiplyWithoutLoop.js
10
rahul#rahul:~/myPractise/Algo$
Is the above code satisfactory or need is there a room for improvement.
Can a better logic be applied.
Hey,
I solved it using recursion,
this is the code,
function multiply01(num,toNum){
var product = num;
return (toNum >= 1) ? product + multiply01(product,--toNum) : 0;
}
Compact way:
function multiply(a, b) {
return a / (1 / b);
}
console.log(multiply(2, 5)); // 10
You could use addition for odd numbers and and bit shifting. Better known as Ancient Egyptian multiplication.
The value of b is summed, if a is odd. Then a is divided by 2 and the integer part is assigned. b is doubled.
Example:
a b sum
--- --- ---
5 4 4 add 4
2 8 4
1 16 20 add 16
0 32 20 <- result
function multiply(a, b) {
var sum = 0;
while (a) {
if (a & 1) {
sum += b;
}
a >>= 1;
b <<= 1;
}
return sum;
}
console.log(multiply(5, 4));
console.log(multiply(3, 7));
console.log(multiply(191, 7));
Please try this, it will also handle negative value
function multiply(x, y)
{
/* Add x one by one */
if(y > 0 )
{
return (x + multiply(x, y-1));
}
/* the case where y is negative */
else if(y < 0 )
{
return -multiply(x, -y);
}
return 0;
}

Categories

Resources