var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
Im not exactly sure where i went wrong here, i am trying to create a function that returns a boolean depending on whether or not a number is even or not.
in order to check if a number is even or not you should check to see if the modulo of 2 with the number is 0. other then that in order to return a value from a function you should use the keyword return. therefor the isEven function should be:
function isEven(num){
return num % 2 === 0;
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));
(even number) % 2 = 0 and with ! you will the 0 as 1 in boolean.
% => module
/ => division
const isEven = number => !(number % 2)
isEven(2) // true
const isOdd = number => !!(number % 2)
isEven(3) // true
In your code :
var i = 1;
var numberCounter = 0
function isEven(num){
if (i % numberCounter === 0) {
console.log('true');
} else { console.log('false');
}
Note that i is equal to 0 and numberCounter is equal to 0. No matter which number is passed in your function, its value won't be considered.
You want to define if a number is odd or even. As a matter of fact the number you want to estimate is the parameter of the function.
A basic definition would be that an odd number can be divided by 2. It means that the remainder of the division is equal to 0.
the if statement concerns the num (passed as parameter) and the remainder.
I took your code and modified it. Saar Davidson answer is much more better and effective (in a single line).
function isEven(num){
if (num % 2 === 0) {
console.log('true');
return true;
} else {
console.log('false');
return false;
}
}
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));
I've started reading Eloquent Javascript, and there's an exercise about making a recursive function to check for evenness.
I've made it in a couple different ways, it's quite simple, but for some reason I can't get it to work with negative numbers anymore. I had it working, then probably accidentally changed something, and now it only works for positives.
Could you please tell me why this code is 'wrong'?
(textfield.append just prints something to a textfield I've made in an html/css-document, so I can save the exercises in some kind of 'program'.)
function evencheck(n){
if (n == 0){
$('#textfield').append('Even');
}
if (n == 1 || n == -1){
$('#textfield').append('Uneven');
}
else{
if(n > 1){
n -= 2;
evencheck(n);
}
if(n < -1){
n += 2;
evencheck(n);
}
}
}
I know it can be written shorter, I've made a shorter form of it, but that didn't work on negatives either.
I know the problem is a stack overflow, but why is this happening?
not an answer but an extended comment
function evencheck(n){
if (n == 0){
return $('#textfield').append('Even');
}
if (n == 1 || n == -1){
return $('#textfield').append('Uneven');
}
return evencheck(n > 1? n-2 : n+2);
}
The upper code will probably be faster, as the compiler can optimize it to:
function evencheck(n){
while(true){
if (n == 0){
return $('#textfield').append('Even');
}
if (n == 1 || n == -1){
return $('#textfield').append('Uneven');
}
n = n>1? n -2 : n+2;
}
}
So youre not filling the function stack ( really huge numbers possible) , and its actually really fast.
More about that
Your code seems to work, except for large numbers. Try it with something like -12 or 10 works fine. When you input 30000 it hangs itself. Probably because you call the method recursively too many times.
const
inputElement = document.getElementById('number-input'),
checkTrigger = document.getElementById('check-number')
resultLog = document.getElementById('result');
function evencheck(n){
if (n == 0){
resultLog.textContent = `${n} is event.`;
}
if (n == 1 || n == -1){
resultLog.textContent = `${n} is unevent.`;
}
else{
if(n > 1){
n -= 2;
evencheck(n);
}
if(n < -1){
n += 2;
evencheck(n);
}
}
}
function checkInputNumber(event) {
const
numberToCheck = parseInt(inputElement.value);
evencheck(numberToCheck);
}
checkTrigger.addEventListener('click', checkInputNumber);
$('#evenrecursive').click(function(){ $('#textfield').append("<p style ='color:blue'>new command: check if number is even.</p>"); var n = prompt('pick a number', ''); evencheck(n); });
#evenrecursive {
border: 1px solid;
min-height: 20px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="number-input" type="number" />
<button type="button" id="check-number">check</button>
<p id="result"></p>
<div id="evenrecursive">click me for prompt.</div>
I've added your trigger and the problem you're having is type coercion. When the initial value of n is "-10" the code winds up in n += 2, this comes down to n = "-10" + 2 which is "-102" and thus your code never reaches the end.
now it only works for positives. why is this happening?
You might be passing a string, in which case n += 2 does do string concatenation instead of number addition (whereas -= 2 always casts to a number). Try adding
if (typeof n != "number") throw new TypeError("n must be a number");
in the first line of the function, and make sure you do use parseInt or some other suitable parsing method if you take a string input from the user.
So I just started studying the Big O notation on my own. I thought I had understood the basics till I wrote a function to check for prime numbers and tried to figure out its time complexity. Here's the code:
function isPrime(num){
if (num === 1 || num%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
else{
for (var i = 2; i < num; i++) {
if (num%i === 0 && i!== 1){ //Checks if any numbers from 2 to are divisible by num
return false
}
}
}
return true;
}
console.log(isPrime(6));
First thing that confused me is whether multiple conditions inside an if statement make any difference or it is just counted once? And then notice I have three return statements. Does that mean I have to include that last line of code where I pass a number to the function to evaluate its time-complexity? Or can I do it without a passed value and calculate for different cases?
function isPrime(n){
if (n === 1 || n%1 !== 0){ //Checks if num is 1 or decimal
return false;
}
for (var i = 2; i < n; i++) {
if (n%i === 0){
return false
}
}
return true;
}
I have made some small refactoring which doesn't change the complexity but makes the code more readable for struggling with Big-O.
So for n > 1, n : orime, the number of operations is:
So the complexity of your algorithm is O(n).
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
}