NaN Result with unique squares - javascript

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);

Related

Transform this iteration function to recursive

This is a function to display the sum of the input digits with iteration perspective:
function sumOfDigits(number) {
let strNumber = number.toString()
let output = 0;
for(i=0;i<strNumber.length;i++){
let tmp = parseInt(strNumber[i])
output = output + tmp
}
return output
}
// TEST CASES
console.log(sumOfDigits(512)); // 8
console.log(sumOfDigits(1542)); // 12
console.log(sumOfDigits(5)); // 5
console.log(sumOfDigits(21)); // 3
console.log(sumOfDigits(11111)); // 5
I am wondering how we write this function in a recursive way?
Using the modulo operator, you can get the remainder (which in the case of a divison by 10, is the last number) and then add the next iteration.
function sumOfDigits (n) {
if (n === 0) return 0
return (n % 10 + sumOfDigits(Math.floor(n / 10)))
}
console.log(sumOfDigits(512))
If you want to see a more detailed explanation, check https://www.geeksforgeeks.org/sum-digit-number-using-recursion/
I have not tested it, but you can try the following without casting to string
function sumOfDigits(number)
{
if (number === 0) {
return 0;
}
return (number % 10 + sumOfDigits(Math.floor(number / 10)));
}
Make sure that the input is indeed in number format
Here you go
function sumOfDigitsRecursive(number){
let strNumber = number.toString()
if(strNumber.length<=0)
return 0
return parseInt(strNumber[0])+sumOfDigitsRecursive(strNumber.slice(1,strNumber.length))
}

making a factorial in javascript with recursion beginner

function nFactorial(n) {
// return the factorial for n
// example:
// the factorial of 3 is 6 (3 * 2 * 1)
if (n < 0){
return;
}
if (sum === undefined){
sum = 1;
}
sum *= n;
nFactorial(n - 1);
return sum;
}
nFactorial(3);
I'm doing my first stab at learning recursion in javascript. I'm trying to solve a problem where I'm making a factorial. I error I get right now is
ReferenceError: sum is not defined
Can anyone point me in the right direction? I'm feeling a little lost.
For using a product as return value, you could use tail call optimization of the recursion by using another parameter for the product (which replaces the sum in the question).
function nFactorial(n, product) {
product = product || 1; // default value
if (n < 0) { // exit condition without value
return;
}
if (n === 0) { // exit condition with result
return product;
}
return nFactorial(n - 1, n * product); // call recursion at the end of function
}
console.log(nFactorial(3));
This approach minimizes the stack length, because the last call does not extend the stack, as opposite of the standard approach of the following recursion without a product parameter.
function nFactorial(n) {
if (n < 0) {
return;
}
if (n === 0) {
return 1;
}
return n * nFactorial(n - 1);
}
console.log(nFactorial(3));
the way you write your code will result always in 0 , here is the correct way for a factorial with recursion, also you need to check if n is a number or the code will trow an error
const factorial =(n)=> {
if(isNaN(n)){
console.log("enter a number")
return 0
}
if(n === 0) {
return 1
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(5));
A simple implementation:
function factorial(n) {
if (n === 1 || n === 0) {
return n;
}
return n * factorial(n-1);
}

Finding remainder of two number without modulus

Instructions: Write a function called "modulo". Given 2 numbers, "modulo" returns the remainder after dividing num1 by num2.
This is my code so far. When I run it on repl.it it gives the correct remainder, but when I submit the program it goes into an infinite loop and I have no clue why. I figure the return functions in the for loop would just automatically exit it. Any help would be appreciated, thanks. Basically I'm adding number2 constantly until it either hits number 1 or goes higher than it. If it goes higher, I subtract number 2 once, and find the difference.
function modulo(num1, num2) {
if(num1 === 0) {
return 0;
}
if(num2 === 0) {
return NaN;
}
if(isNaN(num1) === true || isNaN(num2) === true) {
return NaN;
}
var i = 0;
for( i = 0; i <= num1;) {
i += num2;
if(i === num1) {
return 0;
}
else if(i > num1) {
i = i - num2;
console.log(i, num1);
return num1 - i;
}
}
}
var output = modulo(25, 4);
console.log(output);
function modulo(num1, num2) { var div = num1/num2;
var remainder = div - Math.floor(div); // gives the decimal point value left out from the division
return Math.round(remainder * num2); // multiplies the remainder with num2 and gives a whole number value
}
This is pretty simpler and should work all times
I'm not entirely sure where the infinite loop is showing up; I've plugged your code into console and I can call the function just fine. What site are you using to validate?
Also, without altering too much of your exercise, I'd like to point out a couple of tiny areas where you can consolidate your code to improve readability:
if(num2 === 0) {
return NaN;
}
if(isNaN(num1) === true || isNaN(num2) === true) {
return NaN;
}
can be distilled down into
if (num2 === 0 || isNaN(num1) || isNaN(num2)) {
return NaN;
}
because in JavaScript, booleans work in such a way that everything with a real value is considered to be true, i.e. isNaN(num1) and isNaN(num2) are "true" by default.
Also, remember that you can use all your assignment operators; it's completely optional, but since you used one (i += num2;), I figured I'd point out that you could use another further down the code (i -= num2;).
Happy coding! :)
It could be another option:
function modulo(num1, num2) {
if(isNaN(num1) || isNaN(num2) ) {
return NaN;
}
var strResult = (num1/num2).toString();
var decimalPart =
parseFloat(strResult.substr(strResult.indexOf(".")));
var remainder = Math.round(decimalPart*num2);
return remainder;
}
console.log(modulo(77,9), (77%9)); // 5
console.log(modulo(549,123), (549%123)); // 57
console.log(modulo(33,6), (33%6)); // 3

JS:checking if number belongs to Fibonacci sequence(without loop)

Is there an efficient way to check if number belongs to Fibonacci sequence?
I've seen many examples with a loop that creates the sequence in an array and checks every time if newly generated number of the sequence is equal to the input number. Is there another way?
http://www.geeksforgeeks.org/check-number-fibonacci-number/
This link details that there is a special quality about fibonacci numbers that means that a number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square.
So,
function (num) {
if (isSquare(5*(num*num)-4) || isSquare(5*(num*num)+4)) {
return true;
} else { return false; }
}
Then isSquare would just be a simple checking function.
Edit: Worth noting that while this is a much more efficient and easy way to find fibonacci numbers, it does have an upper bound. At about the 70th Fibonacci number and above, you may see issues because the numbers are too large.
function isFibonacci(num, a = 0, b = 1) {
if(num === 0 || num === 1) {
return true;
}
let nextNumber = a+b;
if(nextNumber === num) {
return true;
}
else if(nextNumber > num) {
return false;
}
return isFibonacci(num, b, nextNumber);
}
function isPerfectSquare(n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
//Equation modified from http://www.geeksforgeeks.org/check-number-fibonacci-number/
function isFibonacci(numberToCheck)
{
// numberToCheck is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
// is a perferct square
return isPerfectSquare(5*numberToCheck*numberToCheck + 4) ||
isPerfectSquare(5*numberToCheck*numberToCheck - 4);
}
for(var i = 0; i<= 10000; ++i) {
console.log(i + " - " + isFibonacci(i));
}
This will most likely fail for larger numbers though.
def is_squared(number):
temp_root = math.sqrt(number);
temp_root = int(temp_root);
return (temp_root * temp_root == number);
def check_all_fibo(test_number_list):
result_fibo_list = [];
for item in test_number_list:
if item==0 or item == 1 or item == 2:
result_fibo_list.append(item);
continue;
if is_squared(5 * item * item - 4) or is_squared(5 * item * item + 4):
result_fibo_list.append(item);
return result_fibo_list;
this is a python implementation by me. But keep in mind, the formula only works when the fib is not too large.
The Fibonacci sequence is a series of numbers where a number is the addition of the last two numbers, starting with 0, and 1. Th following js function is explaining this.
function isFabonacci(n) {
if (n === 1 || n === 0) {
return true;
}
let firstPrevNumber = n - 1;
let secondPrevNumber = n - 2;
return (firstPrevNumber + secondPrevNumber === n);
}
// isFabonacci(2) -> false
// isFabonacci(3) -> true

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.)

Categories

Resources