Last active
December 22, 2018 08:13
-
-
Save tuckcodes/1a16efa11714f9a08f65b1be9c365194 to your computer and use it in GitHub Desktop.
Discern even or odd WITHOUT using the modulo operator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Even or Odd | |
// Determine even or odd WITHOUT the modulo operator | |
// My aim is to add or subtract two from the input until I reach 0 or 1 | |
// If it concludes on 0 it is even, and if on 1 it is odd | |
function determineIfEven(num1) { | |
switch (!isNaN(num1)) { | |
case (num1 == 0): // If the input is 0 then even | |
console.log(true); // Output boolean true | |
break; | |
case (num1 == 1): // If the input is 1 then not even | |
console.log(false); // Output boolean false | |
break; | |
case (num1 > 1 || num1 < 0): // If not 0 or 1 enter this case | |
if (num1 > 1) { // If num1 is greater than 1 then subtract 2 from num1 | |
while (num1 > 1) { // Use loop to preserve the stack, rather than recusive call | |
num1 -= 2; // Subtract 2 until num1 is not greater than 1 | |
} | |
} else { // If num1 is less than 0 then add 2 to num1 | |
while (num1 < 0) { // Loop to preserve stack, rather than recusive call | |
num1 += 2; // Add 2 until num1 is not less than 0 | |
} | |
} | |
determineIfEven(num1); // Recall the function with mutated num1 as parameter | |
default: | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment