This is one of the challenge I have completed in online coding test taking in Codility in Java.
Problem:
The actual problem given to me is, input N is given as random number, I need to find out each number is divisible with 2, 3 and 5. If input N is divisible by 2, 3 and 5, I need to print output as TWO, THREE and FIVE accordingly. If N is divisible by 2 and 3, then need to print output as TWOTHREE. The same will be applicable for others.
If the number is not divisible with any of 2, 3 and 5 then I need to print the number as it is in the output. The sample output would be look like,
Output:
1
TWO
THREE
TWO
FIVE
TWOTHREE
7
Solution:
Here I have placed the source code which will be compatible with Java technology and which meets to all conditions mentioned in above problem. As per my knowledge I have written this code. If anyone can solve in a better way, please share your source code in a comment.
public class DivisionSequence { static int input = 24; public static void main(String[] args) { for (int i = 1; i <= input; i++) { if (i % 2 == 0) { System.out.print("TWO"); if (i % 3 == 0) { System.out.print("THREE"); } if (i % 5 == 0) { System.out.print("FIVE"); } System.out.println(); continue; } if (i % 3 == 0) { System.out.print("THREE"); if (i % 2 == 0) { System.out.print("TWO"); } if (i % 5 == 0) { System.out.print("FIVE"); } System.out.println(); continue; } if (i % 5 == 0) { System.out.print("FIVE"); if (i % 2 == 0) { System.out.print("TWO"); } if (i % 3 == 0) { System.out.print("THREE"); } System.out.println(); continue; } else { System.out.println(i); } } } }
Actual Output:
1 TWO THREE TWO FIVE TWOTHREE 7 TWO THREE TWOFIVE 11 TWOTHREE 13 TWO THREEFIVE TWO 17 TWOTHREE 19 TWOFIVE THREE TWO 23 TWOTHREE
Note: I have taken number 24 as input, you can pass any number as input this program will work for that. All the very best… 🙂