powerofTwo algorithm solution - javascript

Below is my algo to check if number is a power of two. When I run this algo in test case "2" the answer is false. I want to know why it behaves this way ?
var isPowerOfTwo = function(n) {
if(n === 1){
console.log("i came here");
return true;
}
if(n === 0){
return false;
}
if(n%2 === 0){
console.log(n);
n=n/2;
console.log(n);
isPowerOfTwo(n);
}
if(n%2 === 1){
return false;
}
};

You're not returning the recursive call, and you're also changing n before the tests have finished - if n / 2 resolves to 1 then your reassignment of n will result in the bottom if statement running. Use else instead, and don't reassign n, simply pass n / 2 to the recursive call:
var isPowerOfTwo = function(n) {
if (n === 1) return true;
if (n === 0) return false;
if (n % 2 === 0) return isPowerOfTwo(n / 2);
else return false;
};
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Your if (n%2 === 1) return false; condition could result in another bug: what if the initial n was not an integer? Then the function would call itself forever, resulting in an overflow.

Because 1 % 2 === 1
The "problem" is that in the third if you are changing the value of n and not returning any value so it will enter the last if too.

As mentioned, you don't return any value in the 3rd if statement, hence you always get false for values greater than 1 as it will execute the 4th statement too.
In addition to the given answers, here is an interesting solution (initially by Jaromanda X), which I expanded so it deals with if a non-number is passed as a value.
Try cast to a number
const isPowerOfTwo = n => Number(n).toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));
Check the type
const isPowerOfTwo = n => typeof n === 'number' && n.toString(2).split('1').length === 2
console.log(isPowerOfTwo(''));
console.log(isPowerOfTwo('0'));
console.log(isPowerOfTwo('1'));
console.log(isPowerOfTwo('2'));
console.log(isPowerOfTwo(2));
console.log(isPowerOfTwo(8));
console.log(isPowerOfTwo(6));

I think you just need to return an actual value from the n % 2 === 0 branch of your function:
var isPowerOfTwo = function(n) {
if (n === 1) {
console.log("i came here");
return true;
}
else if (n === 0) {
return false;
}
else if (n % 2 === 0) {
console.log(n);
n = n / 2;
console.log(n);
return isPowerOfTwo(n);
}
else { // no need for an if here
return false;
}
};
Note that in the final else we do not need to check anything, because we have already ascertained the number is not a multiple of 2.

Javascript one-liner solution
For any power of 2 (n & n - 1) will return 0. Simple bit-wise operators
isPowerOfTwo = n => !(n & n - 1)
The above function will return true for 0, which is not a power of 2. For that
isPowerOfTwo = n => (n != 0) && !(n & n - 1)

Related

Recursive function to determine if number is even or odd by subtracting two from n until n = 0 or 1

Zero is even.
One is odd.
For any other number N, its evenness is the same as N - 2.
Define a recursive function isEven corresponding to this description. The function should accept a single parameter (a positive, whole number) and return a Boolean.
Here is my implementation of isEven:
let isEven = function(n){
even = 0;
odd = 1;
if(n == even){
return true;
}
else if (n == odd) {
return false;
}
else{
n -= 2;
console.log(n); //Used to see value of n through each call
isEven(n);
}
};
When I call this function, it returns undefined
document.write(isEven(50)); //prints `undefined`
The output from console.log(n) is the following:
Failed to load resource: net::ERR_FILE_NOT_FOUND
48
46
...
0
I am not sure why Failed to load resource: net::ERR_FILE_NOT_FOUND is the first output, but after that n is hitting 0, so why is
if(n == even){
return true;
}?
not executing?
You need to return the result from the recursive call.
let isEven = function(n){
const // declare local variables/constants
even = 0,
odd = 1;
if(n == even){
return true;
}
else if (n == odd) {
return false;
}
else{
//n -= 2; no need to reassign a value for a single use
return isEven(n - 2); // return here
}
};
console.log(isEven(50));
console.log(isEven(21));
A better style without else parts, because this is not necessary if returned before.
use values directly, if used only once,
use strict comparison (Identity/strict equality operator ===), because not strict can led to wrong assumptions
take a calculation for the parameter directly without reassign a value to the variable which is not used anymore
let isEven = function(n){
if (n === 0) return true;
if (n === 1) return false;
return isEven(n - 2);
};
console.log(isEven(50));
console.log(isEven(21));
But don't miss out on the opportunity to learn about mutual recursion!
const isEven = (n = 0) =>
n === 0
? true
: isOdd (n - 1)
const isOdd = (n = 0) =>
n === 0
? false
: isEven (n - 1)
console .log
( isEven (0) // true
, isEven (1) // false
, isEven (2) // true
, isEven (3) // false
, isEven (99) // false
)
console .log
( isOdd (0) // false
, isOdd (1) // true
, isOdd (2) // false
, isOdd (3) // true
, isOdd (99) // true
)

Why is my factorial function returning NaN?

I wrote a factorial function using recursion and a while-loop but it's return value is NaN whenever it is called. Please I want to know why? and how to fix it?
Function
function factorial(n) {
while(n > 0)
return factorial(n - 1) * n;
}
You're missing the return statement for the base case. The function returns undefined when you return without a value, and when you multiply that you get NaN.
Also, you're not looping, so you should use if rather than while.
function factorial(n) {
if (n > 0) {
return factorial(n - 1) * n;
} else {
return 1;
}
}
console.log(factorial(10));
You can also write it with looping instead of recursion.
function factorial(n) {
result = 1;
for (var i = 1; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(10));
If you track your recursion, you'll see when n reaches 1, which make n-1 = 0 and the factorial(0) is called, your function does not know what to do next and does not return any number (NaN). That NaN multiplies with all other things returning another NaN.
Add an instruction for your function in to handle n = 0:
function factorial(n) {
if (n == 0) return 1;
while(n > 0)
return factorial(n - 1) * n;
}
Just add the base case n === 0 to n === 1 to end the tail recursion.
console.log(function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return factorial(n - 1) * n;
}(4));
you can also write it in single line:
const factorial = (n) => (n > 1) ? factorial(n-1) * n : 1

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

Sum of even numbers from 1-100 using recursive function in Javascript

I want to sum even numbers from 1-100 using javascript recursive function, but the output just show me 0 for odd numbers and the number itself for odd numbers
function evenSum(n) {
if (n%2 === 1) {
return 0;
}
else if (n === 100) {
return 100;
}
return n + evenSum(n+1);
}
if (n%2 === 1) {
return 0;
}
That will stop the recursive chain at every second number. For every odd number it will stop directly (and return 0) for every even number it will stop at the second position. Instead, you just want the recursion to continue with the next chain:
if (n%2 === 1) {
return evenSum(n + 1);
}
Actually you can simplify (and speed up the code) if you just go to every second position:
function evenSum(n){
// Stop at 100
if(n >= 100) return 100;
// If it starts at an odd position, go on with the next even
if(n % 2 === 1) return evenSum(n + 1);
// Usually just take every second step:
return n + evenSum(n + 2);
}
That can be shortified to:
const evenSum = n => n >= 100 ? 100 : n % 2 ? evenSum(n + 1) : n + evenSum(n + 2);
You could use a recursion function which count down the values until you reach zero.
The exit condition is a check if the number is smaller or equal to zero, then return the sum otherwise decrement uneven value by one and even value by two and call the function again with the value and temporary sum.
function evenSum(n, s = 0) {
if (n <= 0) {
return s;
}
return evenSum(n - (n % 2 ? 1 : 2), s + n); // tail recursion
}
console.log(evenSum(100));
function evenSum(n) {
if (n <= 1)
return 0;
else
{
if(n%2 === 1)
return evenSum(n - 1);
else
return n + evenSum(n - 1);
}
}
Something like that (works for all numbers, not just 100):
function evenSum(n) {
if (n == 0) return 0; // recursive function needs to stop somewhere
var sum = evenSum(n - 1); // recursive call
if (n % 2 == 0) sum += n; // add current n if it's even
return sum; // return result
}
console.log(evenSum(100));
recursive sum of even number
one line condition
function addOddToN(n) {
return (n <= 2) ? 2 : (n%2 === 0) ? n + addOddToN(n - 1) : addOddToN(n - 1);
}
console.log( addOddToN(100) ); // 2550
console.log( addOddToN(5) ); // 6
console.log( addOddToN(4) ); // 6
console.log( addOddToN(10) ); // 30

Testing whether a value is odd or even

I decided to create simple isEven and isOdd function with a very simple algorithm:
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.
Use modulus:
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
You can check that any value in Javascript can be coerced to a number with:
Number.isFinite(parseFloat(n))
This check should preferably be done outside the isEven and isOdd functions, so you don't have to duplicate error handling in both functions.
I prefer using a bit test:
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
This tests whether the first bit is on which signifies an odd number.
How about the following? I only tested this in IE, but it was quite happy to handle strings representing numbers of any length, actual numbers that were integers or floats, and both functions returned false when passed a boolean, undefined, null, an array or an object. (Up to you whether you want to ignore leading or trailing blanks when a string is passed in - I've assumed they are not ignored and cause both functions to return false.)
function isEven(n) {
return /^-?\d*[02468]$/.test(n);
}
function isOdd(n) {
return /^-?\d*[13579]$/.test(n);
}
Note: there are also negative numbers.
function isOddInteger(n)
{
return isInteger(n) && (n % 2 !== 0);
}
where
function isInteger(n)
{
return n === parseInt(n, 10);
}
Why not just do this:
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
To complete Robert Brisita's bit test .
if ( ~i & 1 ) {
// Even
}
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
A few
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
We just need one line of code for this!
Here a newer and alternative way to do this, using the new ES6 syntax for JS functions, and the one-line syntax for the if-else statement call:
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
A simple modification/improvement of Steve Mayne answer!
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
Note: Returns false if invalid!
Different way:
var isEven = function(number) {
// Your code goes here!
if (((number/2) - Math.floor(number/2)) === 0) {return true;} else {return false;};
};
isEven(69)
Otherway using strings because why not
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
Maybe this?
if(ourNumber % 2 !== 0)
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}
Check if number is even in a line of code:
var iseven=(_)=>_%2==0
This one is more simple!
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
To test whether or not you have a odd or even number, this also works.
const comapare = x => integer(checkNumber(x));
function checkNumber (x) {
if (x % 2 == 0) {
return true;
}
else if (x % 2 != 0) {
return false;
}
}
function integer (x) {
if (x) {
console.log('even');
}
else {
console.log('odd');
}
}
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
when 0/even wanted but
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
​
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}

Categories

Resources