Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create a function that returns Product of Digit Of Sum of a number

I have to create a function that takes two numbers as arguments and adds them together to get a new number. The function then repeatedly multiplies the digits of the new number by each other, yielding a new number, until the product is only 1 digit long. Return the final product.

Example:

sumDigProd(16, 28) ➞ 6
--------------------
// 16 + 28 = 44
// 4 * 4 =  16
// 1 * 6 = 6

I have to sum the numbers in input, but after this i find difficulty to create this algorithm.

Thanks in advance

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This would be one solution:

public int sumDigProd(int nr1, int nr2, boolean initial)
{
    int current = nr1 * nr2;
    if(initial)
    {
        current = nr1 + nr2;
    }

    if(current / 10 % 10 == 0)
    {
        return current;
    }

    int secondDigit = current % 10;
    int firstDigit = current/10 % 10;

    return sumDigProd(firstDigit, secondDigit, false);
}

Then call your function like this:

sumDigProd(16, 28, true)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading