Divisible by 3 and 5
Problem
Read an integer and print one message: Divisible by both 3 and 5, Divisible by 3 only, Divisible by 5 only, or Divisible by neither.
Constraints
- -10^9 <= n <= 10^9
Examples
Input
15
Output
Divisible by both 3 and 5
Input
9
Output
Divisible by 3 only
Solutions
The order of the checks matters: the case with both conditions must be tested first, because a number divisible by both would also match the single checks. The same idea is used in the FizzBuzz problem.
/*
* Problem : Check if a number is divisible by 3, by 5, by both or by neither.
* Input : One integer.
* Output : One of four messages.
* Approach: Use the remainder operator twice.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int number = new Scanner(System.in).nextInt();
// Step 1: A number is divisible by 3 when the remainder of the division by 3 is 0. Same for 5.
boolean by3 = number % 3 == 0;
boolean by5 = number % 5 == 0;
// Step 2: Check the "both" case first. Otherwise the single cases would also match.
if (by3 && by5) {
System.out.println("Divisible by both 3 and 5");
} else if (by3) {
System.out.println("Divisible by 3 only");
} else if (by5) {
System.out.println("Divisible by 5 only");
} else {
System.out.println("Divisible by neither");
}
}
}
Hints (1)
- What happens if you test 'divisible by 3' first?