Ace Shafiq
Ace Shafiq

Reputation: 27

Recursion using modular arithmetic explain java

Could anyone explain how does this method works.

public static int calculate(int n){
if (n/10 == 0)
    return n;
else
    return (n % 10 + calculate(n/10));
} 

I input n = 15 and it get a 6 but I don't understand how the method works. please help. thank you.

Upvotes: 1

Views: 92

Answers (5)

GhostCat
GhostCat

Reputation: 140525

It goes like this:

calculate(15);

evaluates to

15%10 + calculate(1);

evaluates to

5 + 1;

which in the end; sums up to 6.

In other words; the above is an recursive approach to sum all the digits in a number. You could easily re-write this using a simple loop to avoid the recursion construct.

Upvotes: 1

Amit Gujarathi
Amit Gujarathi

Reputation: 1100

In this example there is a if else condition so on the basis of input parameter there are 2 conditions '

-Firstly it checks in the if condition (n/10 == 0) .

-Consider your input as n=15.

  • now it checks if (n/10 == 0) i.e 15/10==0 which is false because 15/10=5 which is not equal to 0.

-As the condition is false it moves to else block where condition is to return (n % 10 + calculate(n/10)

i.e. (15%10 +15/10)==5+1==6 -So the return is 6.

Upvotes: 0

Dishonered
Dishonered

Reputation: 8851

For n = 15 , here is how it works

15/10 > 0 , so the else condition is executed.

15%10 + calculate(15/10) i.e 5 + calculate(1).

The method is called again for n = 1;

Since 1/10 == 0 , 1 is returned

This 1 is then added to 5.

Therefore answer is 6.

So what this function does is return the sum of the digits that make up the number.

Upvotes: 1

Matthias Sommer
Matthias Sommer

Reputation: 1088

It cuts off the most right digit and moves on recursively with the rest of the number. (line 5) If we have only one digit left (line 2), it is also added to the sum and the algorithm ends. (line 3)

Upvotes: 0

Eran
Eran

Reputation: 393936

The method calculates the sum of the digits.

If the n is smaller than 10, you simply return n (since the sum of digits of a single digit number is the number itself).

Otherwise you add the least significant digit (that's n % 10) to the sum of digits of the number n / 10 (which is calculated recursively).

Upvotes: 2

Related Questions