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 am I supposed to loop repeatedly over a "function" in Java?

I have written a code which takes in a number and multiplies it’s digits together and here it is.

public class Happy
    {   public static int findSum(int k)
        {
            int sum = 0;
            while (k != 0)
            {
                sum = sum + ((k % 10)*(k % 10));
                k = k/10;
            }
            return sum;
        }
        public static void main(String args[])
        {
            System.out.println(findSum(713));
        }
    }

and my code returns 19 when my input is 82, because 1^2 + 9^2 is 82.

However, I want to modify my code so that my code would continue to square each digit and add them together until there is only one non-zero digit left.

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

So basically, if my input is 19, the code would return 1 because:

1^2 + 9^2 = 82, from which digits 8 and 2 would do: 8^2 + 2^2 = 68, from which digits 6^2 + 8^2 = 100, from which 1^2 + 0^2 + 0^2 = 1.

What changes to my code should I make in order for it to work?

>Solution :

You could call your method recursivly by checking if sum > 9

public static int findSum(int k)
{
    int sum = 0;
    while (k != 0)
    {
        sum = sum + ((k % 10)*(k % 10));
        k = k/10;
    }
    return sum > 9 ? findSum(sum) : sum;
}
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