From 1 to 100, print "ping" if multiple of 3, "pong" if multiple of 5, or else print the number
Your solution is quite satisfactory IMHO. Tough, as half numbers are not multiple of 3 nor 5, I'd start the other way around:
for (var x=1; x <= 100; x++){
if( x % 3 && x % 5 ) {
document.write(x);
} else {
if( x % 3 == 0 ) {
document.write("ping");
}
if( x % 5 == 0 ) {
document.write("pong");
}
}
document.write('<br>'); //line breaks to enhance output readability
}
Fiddle
Also, note that any number other than 0
and NaN
are truthy values, so I've removed the unnecessary != 0
and some pairs of parenthesis.
Here's another version, it doesn't make the same modulus operation twice but needs to store a variable:
for (var x=1; x <= 100; x++) {
var skip = 0;
if (x % 3 == 0) {
document.write('ping');
skip = 1;
}
if (x % 5 == 0) {
document.write('pong');
skip = 1;
}
if (!skip) {
document.write(x);
}
document.write('<br>'); //line breaks to enhance output readability
}
Fiddle
Here's my one-liner:
for(var x=1;x<101;x++)document.write((((x%3?'':'ping')+(x%5?'':'pong'))||x)+'<br>');
I'm using ternary operators to return either an empty string or 'ping'/'pong'
, concatenating the result of these operators, then doing an OR (if the number is neither divisible by 3 or 5, the result of the concatenation is ''
which is FALSEY in javascript). When both cases are true, the result of the concatenation is 'pingpong'
.
So basically it comes down to
'' || x // returns x
'ping' || x // returns 'ping'
'pong' || x // returns 'pong'
'pingpong' || x // returns 'pingpong'
The best solution I came up with is this one:
for (var i = 1; i <= 100; i++) {
var message = '';
if (i%3 === 0) message += 'ping';
if (i%5 === 0) message += 'pong';
console.log(message || i);
}