I've got a problem with recursion in my code [duplicate] - javascript

I need help creating the code to find the factorial of a number. The task is to
Create a variable to store your answer and initialize it to one
Create a loop that beings at the given value, fact
Check if fact is one or zero
multiply fact with your answer variable
At the end of the loop decrease fact
Print answer using console.log
The pseudocode is
while(factorial)
if factorial == 0 or factorial == 1
break
result => result * factorial
factorial => factorial - 1
My code below isn't complete because I'm confused by the pseudocode.
function nth_fact(nth){
var a = 1
while(nth_fact)
if (nth_fact == 0 || nth_fact == 1){
break;
result => result * nth_fact
nth_fact => nth - 1
console.log()
}
}

At first lets examine what went wrong:
var a = 1
What is a? Its definetly not a good name for a variable. Maybe name it to result ? The same applies to nth which should be named factorial and nth_fact which should rather be factorize or sth. You should also always use ; to end a statement.
while(nth_fact)
As your while loop contains multiple statements (the if and the two assignments) you need to open a block here by using { right after the condition. nth_fact refers to the function, you rather want to take factorial here.
if (nth_fact == 0 || nth_fact == 1){
break;
Now you open a block statement for the if, but you never close it. So you need another } after the break.
result => result * nth_fact
nth_fact => nth - 1
console.log()
=> is the arrow function expression, but you want the assignment operator =. Also you need to pass something to console.log, e.g. console.log(result)
All together:
function factorize(factorial){
var result = 1;
while(factorial){
if (factorial == 0 || factorial == 1){
break;
}
// ?
factorial = factorial - 1;
console.log(result);
}
return result;
}

That pseudocode is indeed confusing, because what it calls factorial is actually not the factorial -- it's the current value, which the result (which is actually the factorial we're looking for) is multiplied by. Also, if is superfluous, because while already checks for the same condition. So the correct pseudocode would be
currentValue = argument
factorial = 1
while (currentValue > 1)
factorial = factorial * currentValue
currentValue = currentValue - 1
// now, 'factorial' is the factorial of the 'argument'
Once you get this sorted out, here's a bonus assignment:
create a function range(a, b) that creates an array of numbers from a to b. For example, range(5, 8) => [5, 6, 7, 8]
create a function product(array) that multiples array elements by each other. For example, product([2, 3, 7]) => 42
write the factorial function using product and range

I solve this this way
function factorial(number) {
let num = 1;
let result = 1;
while (num <= number) {
result = result * num;
num++;
}
return result;
}
const myNumber = factorial(6);
console.log(myNumber);

function factorial(num) {
var result = 1
while (num) {
if ((num) == 0 || (num) == 1) {
break;
} else {
result = result * num;
num = num - 1;
}
}
return `The factorial of ${val} is ${result}`
}
let val = prompt("Please Enter the number : ", "0");
var x = parseInt(val);
console.log(factorial(x));

A Short And Clean Code is :
let number = 5;
let numberFactorial = number;
while(number > 1){
numberFactorial = numberFactorial * (number-1);
number--;
}
console.log(numberFactorial);

function factorize(factorial) {
if(factorial == 0 | factorial == 1) {
return 1
}
else{
var result = factorial;
while(factorial >= 1 ){
if(factorial-1 == 0) {
break
};
result = result * (factorial - 1);
factorial = factorial-1;
//DEBUG: console.log(factorial + ' ' + result);
};
return(result);
}
}
If you want more info about functions, can see in my GitHub, good learning!
Github: https://github.com/bennarthurdev/JavaScript/tree/main/FUNCOES

You used the right approach. Just the syntax was wrong. Here it is:
function nth_fact(nth){
var result = 1 ;
while(nth){
if ((nth) == 0 || (nth) == 1)
break ;
result = result * nth;
nth = nth - 1
}
console.log(result);
return result;
}

Related

Why does my code work in one environment, but not in another?

I'm doing a kata on Codewars. I'm supposed to write a function that returns the index of which number, is not like the others, in evenness(i.e. [1, 2, 4] should return 0). I believe I have a solution, and it proves true when copy/pasting the code, and console.logging on freecodecamps live server, however, when i try to run the code where it is written, it only passes one test. What is going wrong here?
I've tried testing with console.logs, and my solution holds. I know I could just use filter to solve the problem, but i wan't to practice fundamentals.
let odd = [];
let even = [];
function isEven(num) {
if (num % 2 === 0) {
return true;
} else {
return false;
}
}
function iqTest(numbers) {
let nums = numbers.split(' ').map(function(item) {
return parseInt(item, 10);
})
for (let i in nums) {
if (isEven(nums[i])) {
even.push(nums[i])
} else {
odd.push(nums[i])
}
}
if (even.length > odd.length) {
return nums.indexOf(odd[0]) + 1;
} else {
return nums.indexOf(even[0]) + 1;
}
}
The function should accept a string of numbers, one of which will not be either even or odd, then return the index of that number + 1.
You could take the in comments mentioned approach and search for at least one odd and one even and one additional item, at least three items and exit early if this combination is found.
No need to convert the values in advance, because the value get converted to number by using the remainder operator of isEven function.
For a faster return value store the index instead of the value and omit a later indexOf seach.
function isEven(i) { return i % 2 === 0; }
function iqTest(numbers) {
var even = [], odd = [], values = numbers.split(' ');
for (let i = 0; i < values.length; i++) {
(isEven(values[i]) ? even : odd).push(i);
if (even.length && odd.length && even.length + odd.length > 2)
return (even.length < odd.length ? even : odd)[0] + 1;
}
}
console.log(iqTest("1 2 4")); // 1
console.log(iqTest("2 4 7 8 10")) // 3
console.log(iqTest("1 2 1 1")); // 2

Codewars problem 'Happy numbers' how can i make some changes on my code to make it works?

I am working Codewars problem' Happy Numbers ' here is the link https://www.codewars.com/kata/happy-numbers-5/train/javascript Here is the problem, when I am running the code when n > 98 the maximum call stack size is reached. How can I make some changes on my code to fix this problem?
function happyNumbers(x){
var res = [];
for (let i = 1; i <= x; i++){
var str = [];
if (helper(str,i)){res.push(i)}
}
return res
}
function helper(str,n){
var num = 0;
if (n === 1){return true}
if (str.indexOf(n) > -1){return false}
str.push(n);
if (n.toString().length === 1){num = Math.pow(n,2).toString()}
if (n.toString().length >= 2){
num = n.toString().split('')
.reduce((a,b) => Math.pow(a,2)+ Math.pow(b,2)).toString();
}
return helper(str,Number(num))
}
Maybe some more simplyfing would help by
using a Set for visited value to prevent circular loop which never ends (Memoization),
taking numerical values at all, only for splitting into single digits, a string is taken,
summing up by using a simple multiplication,
now some exit function:
check if sum is 1, exit the function with true,
check if sum is already visited and if so, exit with false,
return by calling the function again with sum and updated set visited with sum.
function happyNumbers(x, visited = new Set) {
var sum = 0, value;
for (value of String(x)) sum += value * value;
if (sum === 1) return true;
if (visited.has(sum)) return false;
return happyNumbers(sum, visited.add(sum));
}
console.log(happyNumbers(123));

Javascript Time Complexity Analysis

Hi there I have been researching and trying to learn how to check for the time complexity of certain algorithms. I've seen this video which was very helpful.
That being said I wondered off and started trying to work out the Worsts Case and an average case of certain algorithms.
1
I believe in the following snippet it is O(n) since to ind the value for sin we have to loop the entire array.
function mySin(x, iterNum) {
var mxx = -x*x;
var sin = 1;
var n = 0;
var term = 1;
for (var i = 1; i <= 2*iterNum; i++) {
n = n + 2;
term = term * mxx / ( n*(n+1) );
sin = sin + term
}
sin = x*sin;
console.log(sin + " = my function.");
console.log(Math.sin(x) + " math.sin");
}
Thanks again
2
function calculateFibonacciSum (num) {
if(cachedNumbers[num]) {
return cachedNumbers[num];
}
if(('number' === typeof num) && num <= 0) {
throw new Error ('Fibonnci series starts with 0. Please, enter any interget greater than or equal to 0');
}
else if(('number' === typeof num) && num === 0) {
return 0;
}
else if(('number' === typeof num) && (num === 1 || num === 2)) {
return 1;
}
else {
var value = calculateFibonacciSum(num-1) + calculateFibonacciSum(num-2);
cachedNumbers[num] = value;
return value;
}
}
While for this one I think it is also O(n) since in the first if/else statement the tc is O(1) since its contestant whilst the final else statement we must loop all the numbers and if the number is not calculated then call the function again (aka recurssion).
TIA
Both of these seem correct to me. Here's a bit more explanation:
1.
This is in fact O(n), as there are n iterations of the loop, the rest constant time; and n is proportional to iterNum
2.
This one is also linear time, but only since you cache the results of previous calculations. Otherwise it would be O(2n).
It is linear time since it essentially runs a loop down to the base cases (0 and 1). In fact, you could re-write this one using a loop instead of recursion.

Print the value of the first element that occurs N number of times

So I'm making this ReactJS application.
Part of a filtering system I have the following problem:
Simplified...
I have an array, let's say its simple one like let arr = [1,7,4,3,4,7];
and I also input an N variable from the user that is a simple integer input.
I need to return or console.log() the integers from the array that is repeated N times. If there is nonsuch repeating number log err msg or return -1;
For instance,
let arr = [1,7,4,3,4,7]; and let n = 2; i get 7- cos 7 repeats 2 times
let arr = [7,4,5,3,5,5,3,4,3,2,1]; and let n = 3; i get 5 - cos 5 repeats 3 times
let arr = [1,6,4,6,4,6]; and let n = 4; i get -1 or cl("err") - cos nothing repeats 4 times
Code from comments:
const getRepeatingNumber = (arr, n) => {
for (unit of arr) {
if (unit === maj_unit) count++;
else {
count--;
if (count === 0) {
maj_unit = unit;
count = 1;
}
}
}
return maj_unit;
}
You can use array#every, create an accumulator and place the number as key and its frequency as value, once the value reaches the specified number of occurrence, break from the loop using return false, then return the result.
const getRepeatingNumber = (arr, count) => {
let result = -1, hash = {};
arr.every(n => {
hash[n] = (hash[n] || 0) + 1;
if(hash[n] === count) {
result = n;
return false;
}
return true;
});
return result;
}
console.log(getRepeatingNumber([1,7,4,3,4,7],2));
console.log(getRepeatingNumber([7,4,5,3,5,5,3,4,3,2,1], 3));
console.log(getRepeatingNumber([1,6,4,6,4,6], 4));
Below is the code which will fix your problem I hope.
You need to loop over all array values and find how many time each value occurred and save number of occurrence in a result array because there may be multiple values occurred n number of times. i.e. in your provided array let arr = [1,7,4,3,4,7]; 7 and 4 occurred twice but i am returning result[0] since you might only need first occurred value for n times.
let arr = [1,7,4,3,4,7];
let getRepeatingNumber = function (arr, n) {
let result = [];
arr.forEach((value) => {
if (arr.filter(val => val === value).length === n && !result.includes(value)) {
result.push(value);
}
});
return result.length ? result[0] : -1
}
console.log(getRepeatingNumber(arr, 2)); // 7

Check Odd numbers without modulo operator

I am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));

Categories