• 0

[Java] Need help regarding recursive methods


Question

Wondering if I could get some help on this:

How would you create a recursive method (Either direct or indirect) for multiples.

Let's say I have two variables "a" and "b".

The java application would ask you to input numbers for a and b.

Once you completed inputting numbers it will tell if variable "b" is a multiple of "a" by means of returning or printing a boolean value (true or false).

I tried making this kind of application with the help of "%" but it ended up not being recursive.

Link to comment
Share on other sites

6 answers to this question

Recommended Posts

  • 0

You'd have to have the main program in a loop that keeps running until whatever exit condition is met (exit is typed, etc)

You could use a while loop for that.

Pseudo-Code but should get the point across:

while (have_not_exited == true)
{
if (user_input) = "exit" have_not_exited = false;
int a = (get_user_input);
int b = (get_user_input);
if ((a mod b) = 0)
{
print(b + " is a multiple of " + a);
}
else
{
print(b + " is not a multiple of " + a);
}
}

Link to comment
Share on other sites

  • 0

Substract a from b recursively until b is less than or equal to zero. At this point, if b is equal to 0, b is a multiple of a.

This works if a and b have the same sign. It's pretty simple to deal with the case where they are of opposite signs. ;)

Link to comment
Share on other sites

  • 0

Substract a from b recursively until b is less than or equal to zero. At this point, if b is equal to 0, b is a multiple of a.

This works if a and b have the same sign. It's pretty simple to deal with the case where they are of opposite signs. ;)

What will be the base case for the recursive method?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.