I just came home from a job interview, and the interviewer asked me to write a program:
It should, count from 1 to 100, and print...
If it was multiple of 3, "ping"
If it was multiple of 5, "pong"
Else, print the number.
If it was multiple of 3 AND 5 (like 15), it should print "ping" and "pong".
I chose Javascript, and came up with this:
for (x=1; x <= 100; x++){
if( x % 3 == 0 ){
write("ping")
}
if( x % 5 == 0 ){
write("pong")
}
if( ( x % 3 != 0 ) && ( x % 5 != 0 ) ){
write(x)
}
}
Actualy, I left very unhappy with my solution, but I can't figure out a better one.
Does anyone knows a better way to do that? It's checking twice, I didn't like it. I ran some tests here at home, without success, this is the only one that returns the correct answer...
Use the modulus operator: if (num % 5 == 0) //the number is a multiple of 5. else // the number is not a multiple of 5. Show activity on this post.
The multiples of 5 include 5, 10, 15, 20, 25, 30, 35, 40,…. The multiples of 10 include 10, 20, 30, 40, 50, 60,…. Thus, the common multiples of 5 and 10 are 10, 20, 30, 40,…. That means all the multiples of 10 will be the common multiples for 5 and 10.
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);
}
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With