ays
ays

Reputation: 59

how to determine the multiples of numbers in java

read 2 numbers and determine whether the first one is a multiple of second one.

Upvotes: 4

Views: 51350

Answers (4)

ayush
ayush

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

Martijn Courteaux
Martijn Courteaux

Reputation: 68887

if (first % second == 0) { ... }

Upvotes: 10

Erica
Erica

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:

  • Start
  • Read in the first number and store it
  • Read in the second number and store it
  • Implement the solution you identified in paragraph two using the mathematical operations, and store the result
  • Print the result to the user.

Upvotes: 9

codaddict
codaddict

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

Related Questions