Why the Recursion in the function I declared is not working? - javascript

I am trying to understand recursion.
I am stuck with the following: I need to add up the numbers from a single number so if I call addUp(4) it should return 10 (4+3+2+1).
I came up with the below solution but it does not count the last number (1).
I know that the solution is to change the condition to "num===0" but I don't see the difference: in my head, my solution should work as well.
function addUp(num) {
if (num < 0) {
return num;
}
return num + addUp(num - 1);
}
console.log(addUp(4)); // 9

You need to check for less than or equal to zero. You want to stop if you hit zero as well. A log statement helps identify this.
Alternatively, you could evaluate num < 1.
function addUp(num) {
console.log(`Attempting to add: ${num}`);
if (num <= 0) {
return num;
}
console.log(`Added: ${num}`);
return num + addUp(num - 1);
}
console.log(`Total: ${addUp(4)}`);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Code golf
The following code is only 19 bytes:
f=n=>n<1?n:n+f(n-1)

You can simplify this code and write it in one expression without recursion:
function addUp(num) {
return num*(num+1)/2;
}

The stopping condition should be num <= 0 and not num < 0.
function addUp(num) {
if (num <= 0) {
return num;
}
return num + addUp(num - 1);
}
console.log(addUp(3));
FLOWCHART

Related

Javascript function that finds the next largest palindrome number

I want to write a function that finds the next largest palindrome for a given positive integer. For example:
Input: 2
Output: 3 (every single digit integer is a palindrome)
Input: 180
Output: 181
Input: 17
Output: 22
My try
function nextPalindrome(num) {
let input = num;
let numToStringArray = input.toString().split('');
let reversedArray = numToStringArray.reverse();
if (numToStringArray.length < 2) {
return Number(numToStringArray) + 1;
} else {
while (numToStringArray !== reversedArray) {
// numToStringArray = num.toString().split('');
// reversedArray = numToStringArray.reverse();
num += 1;
}
return numToStringArray.join('');
}
}
As a beginner, I thought that the numToStringArray would constantly increment by 1 and check for whether the while-statement is true.
Unfortunately it doesn't. I commented out two lines in the while-statement because they seemed somewhat redundant to me. Thanks to everyone reading or even helping me out!
The reason your code doesn't work is because you don't have any code updating the conditions of your while loop. So if you enter it once, it will loop indefinitely. You need to do something inside of the while loop that might make the condition false the next time through the loop, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else {
while(num !== getReverse(num)) {
num += 1;
}
return num;
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));
You could also solve this pretty cleanly using recursion, like so:
function getReverse(num) {
// get the reverse of the number (in positive number form)
let reversedNum = +Math.abs(num).toString().split("").reverse().join("");
// keep negative numbers negative
if (num < 0) { reversedNum *= -1; }
return reversedNum;
}
function nextPalindrome(num) {
// if single digit, simply return the next highest integer
if (num >= -10 && num < 9) {
return num+1;
}
else if(num === getReverse(num)) {
return num;
}
else {
// if not the same, recurse with n + 1
return nextPalindrome(num + 1)
}
}
console.log(nextPalindrome(3));
console.log(nextPalindrome(17));
console.log(nextPalindrome(72));
console.log(nextPalindrome(180));
console.log(nextPalindrome(1005));
console.log(nextPalindrome(-150));
console.log(nextPalindrome(-10));

Summing all primes in a number: 9 returns true

I am currently stuck with this challenge: https://www.freecodecamp.org/challenges/sum-all-primes
I am trying to sum all the prime numbers from 0 to 10
I have a function to check if the number is a prime number. If I pass 9 it returns false which is good.
However when I am decrementing from 10 with a while loop and it passes 9 into the function it seems to be returning true and adding it to my sum. As a result I get the result of 24 when the sum of all the prime numbers in 10 is 17! This is because it is adding 9 as a prime number.
Here is my code, I must be missing something obviouse here but I can figure it out!
function sumPrimes(num) {
function isPrime() {
for (var i = 2; i <= num; i++) {
if (num % i === 0) {
return false;
}
return num !== 1;
}
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
console.log(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
Firstly you need to return true from isPrime() if no number less than num divides the number so remove return num !== 1; from inside the for loop and add return true after the loop. Also you are running the loop in function isPrime() till the number num, since every number is divisible by itself, function will return false for every number, change for loop condition to i<num. Also note that 1 is not a prime number so you don't need to add it in the sum.
function sumPrimes(num) {
function isPrime(num){
if(num === 1 ) //since 1 is neither prime nor composite.
return false;
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
// alert(isPrime(9)); // returns false
var count = 0;
while (num >= 0) {
if (isPrime(num)) {
count += num;
alert(count);
}
num--;
}
console.log(count);
}
sumPrimes(10);
try to modify the following code snippet
function isPrime() {
for (var i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {return false;}
}
return true;
}
Using Math.sqrt(num) as an upper limit will improve time complexity and speed up the computation for large numbers (see my online Prime Numbers Calculator up to 18 digits implementing this algo with some additional optimization: http://examn8.com/Primes.aspx )
Hope this may help.

Returning factorials in JavaScript

I'm trying to create a script that returns the factorial of the input number as part of a challenge. When I try to run it, it returns the proper factorial, but apparently I did it wrong somehow.
It looks like this:
function FirstFactorial(num) {
if (num > 1) {
var x = num;
for (var i = 1; i < x; i++) {
num = num * i;
}
} else if (num === 1) {
return 1;
} else {
console.log("That's not a number!");
}
return num;
}
Then I tried doing it like this, but it still doesn't work!
function FirstFactorial(num) {
if (num < 0) {
num = 0;
console.log("You have to input a number!");
}
if (num === 0) {
return 1;
}
return num * FirstFactorial(num - 1);
}
The most likely reason is that they expected and intended you to use recursion (a function that calls itself).
If you think about factorials, each builds on the result of the previous one, which is the classic case for using recursion.
(Note that I'm specifically not posting code doing this with recursion, because presumably the point here is for you to work out how to do it.)

NaN Result with unique squares

I am writing a function in Javascript that would take in a number, then return how many squares there are in a square with sides that long. For example, passing through 1 would give you one, 2 would give you 5, 3 would give you 14 and so forth. The problem is, I'm getting a result of Nan. I'm not sure where it would have gotten anything besides a number from.
function a (n)
{
if (n > 0)
{
var total = n*n;
total += a(n-1);
return (total);
}
}
document.write(a(10));
I'm not sure where it would have gotten anything besides a number from.
Your base case is missing, it returns undefined. Try
function a(n) {
if (n > 0)
return n*n + a(n-1);
else
return 0;
}
It's because of the if (n > 0) When this is not true your function returns void. So return 0 on your else.
function a (n)
{
if (n > 0)
{
var total = n*n;
total += a(n-1);
return total;
}
else
{
return 0;
}
}
console.log(a(10));
You already have two good answers. I just want to make you aware of writing in a more Object Oriented style. If things get more complicated it is easier to group the variables and functions together and keep them toghether away from all your other stuff. I would write something like this to keep it organized:
var a = {
total: 0,
sides: function (n) {
if (n > 0) {
this.total = n * n;
this.total += this.sides(n - 1);
return this.total;
} else {
return 0
}
}
}
a.sides(5);
alert(a.total);

Using conditionals inside a loop

I am trying to achieve a check with the if...else statement that only squares the odd numbers between 100 and 150, otherwise the number is just printed.
How can I revise my if statement to achieve this please? An educated guess is that an operator or combination of operators are used.
for (i=100; i<=150; i++)
{
if (i === 0)
{
console.log(i * i);
}
else
{
console.log(i);
}
}
The operator you are looking for is %:
for(i = 100; i <= 150; i++) {
if(i % 2 === 1) { // It's odd
console.log(i * i);
} else {
console.log(i);
}
}
a % b is basically the remainder obtained when a is divided by b. It's called the modulus operator.
Two words: Modulus Division
A nice reference
if ( i % 2 === 0) {
console.log(i)
} else {
console.log(i * i)
}
Squares odd numbers.

Categories

Resources