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.
Examples:
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.
Solution:
The solution is simple. we just have to iterate from 1 to n and have to track the multiples of 3 and 5 by adding 3 and 5 to the current multiple.If the current number you get matches with a multiple then we update our result accordingly.
Sample Code:
/**
* @author Abhinaw.Tripathi
*
*/
public class MultipleOfThreeAndFive
{
public static void findMultiple(int n)
{
int a = 3;
int b = 5;
for (int i=1; i<=n; i++)
{
String s = "";
if (i==a)
{
a = a + 3;
s = s + "Multiple of 3. ";
}
if (i==b)
{
b = b+5;
s = s + "Multiple of 5.";
}
if (s == "")
System.out.println(i);
else System.out.println(s);
}
}
public static void main(String[] args)
{
findMultiple(20);
}
}
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.
16
17
Multiple of 3.
19
Multiple of 5.
No comments:
Post a Comment