Write a short program that prints each number from 1 to n on a new line.
- For each multiple of 3, print “Multiple of 3” instead of the number.
- For each multiple of 5, print “Multiple of 5” instead of the number.
- For numbers which are multiples of both 3 and 5, print “Multiple of 3. Multiple of 5.” instead of the number.
Input : 15 Output : 1 2 Multiple of 3. 4 Multiple of 5. Multiple of 3. 7 8 Multiple of 3. Multiple of 5. 11 Multiple of 3. 13 14 Multiple of 3. Multiple of 5.
The idea is iterate from 1 to n and keep track of multiples of 3 and 5 by adding 3 and 5 to current multiple. If current number matches with a multiple, we update our output accordingly.
1 2 Multiple of 3. 4 Multiple of 5. Multiple of 3. 7 8 Multiple of 3. Multiple of 5. 11 Multiple of 3. 13 14 Multiple of 3. Multiple of 5. 16 17 Multiple of 3. 19 Multiple of 5.
This article is contributed by Nimish Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- || operator in Java
- new operator in Java
- & Operator in Java with Examples
- && operator in Java with Examples
- Difference between concat() and + operator in Java
- new operator vs newInstance() method in Java
- Java Ternary Operator Puzzle
- Double colon (::) operator in Java
- Decimal to Binary using recursion and without using power operator
- instanceof operator vs isInstance() method in Java
- Queries to find the count of characters preceding the given location
- Find the path from root to the given nodes of a tree for multiple queries
- Count number of steps to cover a distance if steps can be taken in powers of 2
- LogRecord setSourceMethodName() method in Java with Examples