Home > Mobile >  How can I make this code faster where I have to print the total of odds of a given number?
How can I make this code faster where I have to print the total of odds of a given number?

Time:04-09

The problem is: Print out how much odd numbers there are in a given number.

function oddCount(n) {
  var odd = [];
  for (i = 0; i < n; i  ) {
    if (i % 2 == 1) {
      odd.push([i]);
    }
  }
  return odd.length;
}
console.log(oddCount(8));

As we can see, it works properly, however, on codewars, it wants me to optimize it to run faster. Can someone show me how so I can learn it quickly please.

CodePudding user response:

function oddCount(n) {
  var odd = [];
  for (i = 0; i < n; i  ) {
    if (i & 0x1 == 1) {
      odd.push([i]);
    }
  }
  return odd.length;
}
console.log(oddCount(8));

or

function oddCount(n) {
   return (n - (n & 0x01)) / 2;
}
console.log(oddCount(8));

CodePudding user response:

You could defently spare a lot if you just count the odd numbers, and not passing them to an array first, just for getting the length of the array afterwards :

function oddCount(n) {
  let odds = 0
  for(let i=0; i<n; i  ) {
    if (i%2 === 1) odds  
  }
  return odds
}

CodePudding user response:

I believe this should work.

function oddCount(n) {
  return Math.ceil(n/2);
}
console.log(oddCount(8));

CodePudding user response:

If the number is an even number, there's n/2 odd numbers Eg if n is 6 *1*,2,*3*,4,*5*,6 If it is an odd number, there's n/2 1 odd numbers. Because n-1 would be even Eg if n is 5 *1*,2,*3*,4, *5* So basically

if (n%2==0) return n/2
else return (n-1)/2 1

The for loops aren't needed Also like the others pointed out, ceiling is a more concise way to do it

return Math.ceil(n/2)

CodePudding user response:

Neither "ceil" or "floor" is a correct answer as a one liner. "ceil" will make the division Base 1, "floor" will make the division Base 0. So both could be used in an implementation, but the "polarity" of n matters.

It's necessary to check whether the input number is odd or even.

function oddCount(n) {

   // odd / even check
   if (n % 2 == 0) {
     // its even, we can divide by 2
     return n / 2
   }
   else {
     // n is odd, so we must include n as a count 1 itself
     return ((n - 1) / 2)   1
   }
}

// Disclaimer: Are negative numbers odd or even? In this code they
// apparently aren't handled. So the set of numbers are integers from
// 0 to  Infinity

// Test cases:

console.log( oddCount(8) ); // 4
console.log( oddCount(9) ); // 5

But this code "breaks" if n itself is 0 or less. So we need to fix it:

Right after we say function oddCount(n) {, put:

if (n < 1) return 0;

All worries solved. But still debate on whether 0 is odd or even, and whether -1 is odd and -2 is even.

  • Related