Checking divisibility and converting digits into text - javascript

Check the divisibility of 2, 3, and both 2 and 3
Divisible by 2 - print x
Divisible by 3 - print y
Divisible by 2 and 3 - print xy
let num = prompt('1-1000');
if (num %2 == 0 )
{
console.log("X")
}
if (num %3 == 0 )
{
console.log("Y")
}
if (num %3 == 0 && num %2 ==0)
{
console.log("XY")
}
Example:
Input: 6
Output:
X
Y
XY
How to make it not print X, Y but XY?
What needs to be done so that several digits to be checked after the decimal point can be entered and then converted to the appropriate letters?

There are a couple of ways you could do this.
One way would be to use a ternary operator to output the values X and/or Y. This will have X logged only when divisible by 2, and Y only logged when divisible by 3. If it is divisible by both, both are shown but their conditions are independent of each other. And using template literals it is concatenated into 1 value.
let num = prompt('1-1000');
console.log(`${(num%2==0)?"X":""}${(num%3==0)?"Y":""}`);
Alternatively, you could use something like what was mentioned in the comments. If you convert the code to a function, you can move the final if statement to the top and use exit/return statements to return only 1 of the values (whichever applies).
const _Check = () => {
let num = prompt('1-1000');
if(num % 3 == 0 && num % 2 == 0) return "XY";
if(num % 2 == 0 ) return "X";
if(num % 3 == 0 ) return "Y";
return "";
}
console.log(_Check());
EDIT
In reponse to a comment by OP: checking for multiple numbers could be done by splitting the value input by the user and then looping through those values.
If the user will be inputting each number separated by a space, you can use the split() method with a space as the separator. And then use forEach() to loop through each number and apply the code/logic we have used earlier.
Example Using ternary operator and template literals:
let num = prompt('1-1000')
num.split(" ").forEach(n => {
console.log(`${(n%2==0)?"X":""}${(n%3==0)?"Y":""}`);
})
Example using a function and return statements:
let num = prompt('1-1000')
const _Check = n => {
if(n %3 == 0 && n %2 ==0) return "XY";
if(n %2 == 0 ) return "X";
if(n %3 == 0 ) return "Y";
return "";
}
num.split(" ").forEach(n => {
console.log(_Check(n));
})

Related

I have made a simple calculator but How I can prevent users from entering dot several times in one number ? so far i can only prevent double dots

if
(previousNum == "." && currentNum == ".") {
screen.value = screen.value.substring(0, numchar - 1);
You are using javascript. you can split it on "." then count the length of the array which should be 2 or less.
var x = '12.34.56';
var arr = x.split(".")
var number_of_dots = arr.length - 1
console.log(number_of_dots)
I think you can check if the number is Integer or float with this sample function
function isFloat(n){
return Number(n) === n && n % 1 !== 0;
}
function isInt(n) {
return n % 1 === 0;
}
and write catch, so if had error the entered number is not valid for you calculator

Why do both these two solutions for printing all numbers divisible by 3 AND 5 between 5 and 50 work?

This was my solution to the problem:
var count = 5;
while (count <= 50) {
if ((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This was my the instructors solution:
var count = 5;
while (count <= 50) {
if (count % 3 === 0 && count % 5 === 0) {
console.log(count);
}
count++;
}
Both of these solutions gave the proper answer, but I question why || worked in my problem, rather than &&, I tried both. && means both need to be true for it to properly run, right? So wouldn't that have been the proper use?
var count = 5;
while(count <= 50) {
console.log(`count = ${count} | (count % 3 || count % 5) = ${(count % 3 || count % 5)}`);
if((count % 3 || count % 5) === 0) {
console.log(count);
}
count++;
}
This happens because in all cases where count % 3 === 0 and count % 5 does not, the number takes precedence in the or (||) statement since it's "truthy".
eg.
count = 6, 0 || 1 // 1, since 0 is "falsy"
count = 8, 2 || 3 // 2
count = 15, 0 || 0 // 0
Therefore, it seems you stumbled on the correct solution.
It is a javascript peculiarity you encounter. If count % 3 is 0 it is considered "falsy" and the other calculation will be used. So if either modulus has a remains, that value is used in the final test against 0.
So while both works, your teachers code is more readable; thus better.
The following code
(count % 3 || count % 5) === 0
evaluates first the % operations and then the or to end with ===. If both modulo operations return 0, the or condition also evaluates as 0, that compared with 0 equals true and print the numbers. Otherwise, if any of the modulo values isn't 0, the or operation will result in these numbers, hence it won't be printed.
This is because Javascript evaluates numeric values as boolean being 0 False, and any other value True.
In your case it's a question of parenthesis
1st case of || with parenthesis like this ((count % 3 || count % 5) === 0) it like you say count has to be % by 3 and 5 so it's like &&
2nd case (count % 3 === 0 && count % 5 === 0) you've changed the parenthesis to regroup all
with && in the middle
so as i said it's question of parenthesis that makes both solution give the same result
Every value except 0 is evaluated as true. If there is a number divisible by 3 AND 5 both, then 0 || 0 is 0, which makes your if condition to run. If there is a number that is only divisible by 3 OR 5, lets say 10, then 10%3 is equal to 10 and 10%5 is equal 0. 10 || 0 will be evaluated as true (non-zero). Since non-zero value is not equal to 0 therefore if condition will not execute.
I am not sure but your instructors expression can be said as created from your expression by using Demorgans law.
The second solution is more useful than the first.
Because always "%" operator is computational, not logical

Check whether a number is divisible by another number If not make it divisable in Javascript

I want to check whether a number (7) is divisible by another number (5), If the number is divisible by the number then I need to return the same number. If the number is not divisible by another number I need to make it divisible and return the updated value.
var i =7;
if (i % 5 == 0) {
alert("divisible by 5");
} else {
alert("divisible not by 5");
}
Here if the condition satisfy then I need to return the same value. If the condition is not satisfied I need to add the required number and make it next divisible. (Like 7 is not divisible by 5 so I need add 3 to 7 and return the value 10 which is divisible by 5).
Are there any Math functions exists to implement the same?
What you want, it seems like, is this:
function roundTo(n, d) {
return Math.floor((n + d - 1) / d) * d;
}
For n 10 and d 5, you get 10 back. For n 7 and d 5, you also get 10. What the code does is add one less than the divisor to the input number, and then divides by the divisor. It then gets rid of any fractional part (Math.floor()) and multiplies by the divisor again.
You can do that by using a simple while loop:
function doThat(number, divider) {
while(number % divider !== 0) {
number++;
}
return number;
}
doThat(12, 5); // => returns 15
Here's a fiddle: https://jsfiddle.net/rdko8dmb/
You could use this algorithm:
i % n = r, where i = 7, n = 5, and r = 2.
Then, make i = i + (n - r). i.e. i = 7 + (5-2) → 10. Then you can use this for your division.
Try this
function divisible(dividend, divisor){
if (dividend % divisor == 0) {
return dividend;
} else {
var num = dividend + (divisor-(dividend % divisor));
return num;
}
}
var res = divisible(7, 5);
console.log(res);
Here is the fastest and cleanest way to do that:
function shift(number, divider)
{
return number + (divider - (number % divider)) % divider;
}
It takes number and moves it up by the difference from (our unit) divider to the remainder to make it divisible by the divider. The % divider makes sure that if there is no difference number doesn't get pushed up by a full unit of the divider.
I do not know if this will work for all numbers... But you might try this
7 % 5 = 2. If you subtract 2 from 5 you will get 3... This is the number you need to add to 7. 16 % 5 = 1 subtract 1 from 5 = 4 .. 4 + 16 = 20
Another example 16 % 13 = 3 ... 13-3 = 10 16+10 = 26 26/13 = 2
Here's an example of function that finds next higher natural number that is divisble by y
https://www.jschallenger.com/javascript-basics/find-next-higher-number
Option 1
while (x % y !== 0) x++;
return x;
}
Option 2
if(x % y == 0){
return x;
}
else{
for(i = x+1; i > x; i++){
if(i % y == 0){
return i;
}
}
}

Boolean expressions - getting mixed up with AND, OR logical operators and how they work

I have to convert a number to comma format. E.g 12345 => 12,345.
I have my solution :
function convert(n) {
n = n.toString();
var result = '';
var count = 0,
var idx = n.length - 1;
while (r = n[idx]) {
count++;
result = ((count % 3 == 0 && count != n.length) ? ',' : '') + r + result;
idx--;
}
return result;
}
But someone else used :
result = ((count % 3 != 0 || count == n.length) ? '' : ',') + r + result;
They both work but now I am confused about my own solution and just lost why they both work. Ah not sure if my question is clear.
!(x AND y) is equal to !x OR !y
(and you can pull a NOT out of a boolean x by double negation, for example:
x == !!x
so
x AND !y (your original expression) is equivalent to !(!x OR y)
if you remove the negation (!) from the beginning, then you actually get the Negated form and that is why the second and third values of the ternary operator are reversed in your second example.
The two expressions are equivalent, the second one is just the negated version of yours. The opposite (more or less) of == is !=, the opposite of && is ||, and the opposite of true is false.
You are placing a comma whenever the count is divisible by 3 and you aren't at the start of the number. They are not placing a comma anytime the count is not divisible by 3 or they are at the start of the number.
Assume that, count % 3 = 0 and count > n.length
Now your logic:
((count % 3 == 0 && count != n.length) ? ',' : '')
which means True && True which results in True hence the first condition after ? which is "," is selected.
Someone else logic:
((count % 3 != 0 || count == n.length) ? '' : ',')
which means 'False || False' which results in 'False' hence second condition after ? which is "," is selected.
P.S: Both are using similar logic

How do I know if a number is odd or even in JS? [duplicate]

Can anyone point me to some code to determine if a number in JavaScript is even or odd?
Use the below code:
function isOdd(num) { return num % 2;}
console.log("1 is " + isOdd(1));
console.log("2 is " + isOdd(2));
console.log("3 is " + isOdd(3));
console.log("4 is " + isOdd(4));
1 represents an odd number, while 0 represents an even number.
Use the bitwise AND operator.
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
function checkNumber(argNumber) {
document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}
checkNumber(17);
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
If you don't want a string return value, but rather a boolean one, use this:
var isOdd = function(x) { return x & 1; };
var isEven = function(x) { return !( x & 1 ); };
You could do something like this:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
Do I have to make an array really large that has a lot of even numbers
No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.
Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.
This can be solved with a small snippet of code:
function isEven(value) {
return !(value % 2)
}
Hope this helps :)
In ES6:
const isOdd = num => num % 2 == 1;
Like many languages, Javascript has a modulus operator %, that finds the remainder of division. If there is no remainder after division by 2, a number is even:
// this expression is true if "number" is even, false otherwise
(number % 2 == 0)
Similarly, if there is a remainder of 1 after division by 2, a number is odd:
// this expression is true if "number" is odd, false otherwise
(number % 2 == 1)
This is a very common idiom for testing for even integers.
With bitwise, codegolfing:
var isEven=n=>(n&1)?"odd":"even";
Use my extensions :
Number.prototype.isEven=function(){
return this % 2===0;
};
Number.prototype.isOdd=function(){
return !this.isEven();
}
then
var a=5;
a.isEven();
==False
a.isOdd();
==True
if you are not sure if it is a Number , test it by the following branching :
if(a.isOdd){
a.isOdd();
}
UPDATE :
if you would not use variable :
(5).isOdd()
Performance :
It turns out that Procedural paradigm is better than OOP paradigm .
By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .
A simple function you can pass around. Uses the modulo operator %:
var is_even = function(x) {
return !(x % 2);
}
is_even(3)
false
is_even(6)
true
if (X % 2 === 0){
} else {
}
Replace X with your number (can come from a variable). The If statement runs when the number is even, the Else when it is odd.
If you just want to know if any given number is odd:
if (X % 2 !== 0){
}
Again, replace X with a number or variable.
<script>
function even_odd(){
var num = document.getElementById('number').value;
if ( num % 2){
document.getElementById('result').innerHTML = "Entered Number is Odd";
}
else{
document.getElementById('result').innerHTML = "Entered Number is Even";
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Find Given Number is Even or Odd </h2>
<p>Enter a value</p>
<input type="text" id="number" />
<button onclick="even_odd();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
Many people misunderstand the meaning of odd
isOdd("str") should be false.
Only an integer can be odd.
isOdd(1.223) and isOdd(-1.223) should be false.
A float is not an integer.
isOdd(0) should be false.
Zero is an even integer (https://en.wikipedia.org/wiki/Parity_of_zero).
isOdd(-1) should be true.
It's an odd integer.
Solution
function isOdd(n) {
// Must be a number
if (isNaN(n)) {
return false;
}
// Number must not be a float
if ((n % 1) !== 0) {
return false;
}
// Integer must not be equal to zero
if (n === 0) {
return false;
}
// Integer must be odd
if ((n % 2) !== 0) {
return true;
}
return false;
}
JS Fiddle (if needed): https://jsfiddle.net/9dzdv593/8/
1-liner
Javascript 1-liner solution. For those who don't care about readability.
const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;
You can use a for statement and a conditional to determine if a number or series of numbers is odd:
for (var i=1; i<=5; i++)
if (i%2 !== 0) {
console.log(i)
}
This will print every odd number between 1 and 5.
Just executed this one in Adobe Dreamweaver..it works perfectly.
i used if (isNaN(mynmb))
to check if the given Value is a number or not,
and i also used Math.abs(mynmb%2) to convert negative number to positive and calculate
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body bgcolor = "#FFFFCC">
<h3 align ="center"> ODD OR EVEN </h3><table cellspacing = "2" cellpadding = "5" bgcolor="palegreen">
<form name = formtwo>
<td align = "center">
<center><BR />Enter a number:
<input type=text id="enter" name=enter maxlength="10" />
<input type=button name = b3 value = "Click Here" onClick = compute() />
<b>is<b>
<input type=text id="outtxt" name=output size="5" value="" disabled /> </b></b></center><b><b>
<BR /><BR />
</b></b></td></form>
</table>
<script type='text/javascript'>
function compute()
{
var enter = document.getElementById("enter");
var outtxt = document.getElementById("outtxt");
var mynmb = enter.value;
if (isNaN(mynmb))
{
outtxt.value = "error !!!";
alert( 'please enter a valid number');
enter.focus();
return;
}
else
{
if ( mynmb%2 == 0 ) { outtxt.value = "Even"; }
if ( Math.abs(mynmb%2) == 1 ) { outtxt.value = "Odd"; }
}
}
</script>
</body>
</html>
When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).
function isOdd(value) {
return typeof value === "number" && // value should be a number
isFinite(value) && // value should be finite
Math.floor(value) === value && // value should be integer
value % 2 !== 0; // value should not be even
}
If Number.isInteger is available, you may also simplify this code to:
function isOdd(value) {
return Number.isInteger(value) // value should be integer
value % 2 !== 0; // value should not be even
}
Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.
Here are some test cases:
isOdd(); // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN); // false
isOdd(0); // false
isOdd(1.1); // false
isOdd("1"); // false
isOdd(1); // true
isOdd(-1); // true
Using % will help you to do this...
You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:
odd function:
var isOdd = function(num) {
return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};
even function:
var isEven = function(num) {
return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};
and call it like this:
isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true
A more functional approach in modern javascript:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const negate = f=> (...args)=> !f(...args)
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)
One liner in ES6 just because it's clean.
const isEven = (num) => num % 2 == 0;
Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)
Every odd number when divided by two leaves remainder as 1 and every even number when divided by zero leaves a zero as remainder. Hence we can use this code
function checker(number) {
return number%2==0?even:odd;
}
How about this...
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
This is what I did
//Array of numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32,23,643,67,5876,6345,34,3453];
//Array of even numbers
var evenNumbers = [];
//Array of odd numbers
var oddNumbers = [];
function classifyNumbers(arr){
//go through the numbers one by one
for(var i=0; i<=arr.length-1; i++){
if (arr[i] % 2 == 0 ){
//Push the number to the evenNumbers array
evenNumbers.push(arr[i]);
} else {
//Push the number to the oddNumbers array
oddNumbers.push(arr[i]);
}
}
}
classifyNumbers(numbers);
console.log('Even numbers: ' + evenNumbers);
console.log('Odd numbers: ' + oddNumbers);
For some reason I had to make sure the length of the array is less by one. When I don't do that, I get "undefined" in the last element of the oddNumbers array.
I'd implement this to return a boolean:
function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
It'll work on both unsigned and signed numbers. When the modulus return -1 or 1 it'll get translated to true.
Non-modulus solution:
var is_finite = isFinite;
var is_nan = isNaN;
function isOdd (discriminant) {
if (is_nan(discriminant) && !is_finite(discriminant)) {
return false;
}
// Unsigned numbers
if (discriminant >= 0) {
while (discriminant >= 1) discriminant -= 2;
// Signed numbers
} else {
if (discriminant === -1) return true;
while (discriminant <= -1) discriminant += 2;
}
return !!discriminant;
}
By using ternary operator, you we can find the odd even numbers:
var num = 2;
result = (num % 2 == 0) ? 'even' : 'odd'
console.log(result);
Another example using the filter() method:
let even = arr.filter(val => {
return val % 2 === 0;
});
// even = [2,4,6]
So many answers here but i just have to mention one point.
Normally it's best to use the modulo operator like % 2 but you can also use the bitwise operator like & 1. They both would yield the same outcome. However their precedences are different. Say if you need a piece of code like
i%2 === p ? n : -n
it's just fine but with the bitwise operator you have to do it like
(i&1) === p ? n : -n
So there is that.
this works for arrays:
function evenOrOdd(numbers) {
const evenNumbers = [];
const oddNumbers = [];
numbers.forEach(number => {
if (number % 2 === 0) {
evenNumbers.push(number);
} else {
oddNumbers.push(number);
}
});
console.log("Even: " + evenNumbers + "\nOdd: " + oddNumbers);
}
evenOrOdd([1, 4, 9, 21, 41, 92]);
this should log out:
4,92
1,9,21,41
for just a number:
function evenOrOdd(number) {
if (number % 2 === 0) {
return "even";
}
return "odd";
}
console.log(evenOrOdd(4));
this should output even to the console
A Method to know if the number is odd
let numbers = [11, 20, 2, 5, 17, 10];
let n = numbers.filter((ele) => ele % 2 != 0);
console.log(n);

Categories

Resources