Reputation: 59
read 2 numbers and determine whether the first one is a multiple of second one.
Upvotes: 4
Views: 51350
Reputation: 73
//To check if num1 is a multiple of num2
import java.util.Scanner;
public class multiples {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number!");
int num1 = reader.nextInt();
reader.nextLine();
System.out.println("Enter another number!");
int num2 = reader.nextInt();
if ((num1 % num2) == 0) {
System.out.println("Yes! " + num1 + " is a multiple of " + num2 + "!");
} else {
System.out.println("No! " + num1 + " is not a multiple of " + num2 + "!");
}
reader.close();
}
}
Upvotes: 2
Reputation: 2251
Given that this is almost certainly a homework question...
The first thing you need to think about is how you would do this if you didn't have a computer in front of you. If I asked you "is 8 a multiple of 2", how would you go about solving it? Would that same solution work if I asked you "is 4882730048987" a multiple of 3"?
If you've figured out the math which would allow you to get an answer with just a pen and paper (or even a pocket calculator), then the next step is to figure out how to turn that into code.
Such a program would look a bit like this:
Upvotes: 9
Reputation: 455272
A number x
is a multiple of y
if and only if the reminder after dividing x
with y
is 0
.
In Java the modulus operator(%
) is used to get the reminder after the division. So x % y
gives the reminder when x
is divided by y
.
Upvotes: 1