Ad Home

Theme images by kelvinjay. Powered by Blogger.

Travel

Header Ads

Java

Selenium

UFT

Framework

General QA Concept

BDD

» » Find all numbers which are equal to the sum of the factorial of their digits


Hope you have enjoyed http://www.askqtp.com/2011/12/factorial-how-i-coded-it.html
Now let me find out some number in such a way that sum of factorial of each digit of that number is equal to that number.
like-145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145
So the logic is --
1.Get the number
2. Find out each digit of that number
3. Find out factorial of that number
4. Sum of the factorials
5. Check if the original input is equal to the sum
6. if they matches print the result.

How to code:

1. get user input..

Please go through
http://www.askqtp.com/2011/12/how-to-take-user-input-in-java-how-i.html

2. Now I need to create a logic that will give me the digits from a number.

private void getDigit(int number)
    {
   
      int tmp = 1;
      while(number > 0)
         {
          tmp = number % 10;
          number /= 10;
System.out.println(tmp );
          }
     }
So now we have the numbers of each digit.

3.Find out factorial of that number



4. Sum of the factorials

so after getting factorials for each digit we need to sum these.let me write a function for it which will call factorial method and sum them up.
        private int addfactOfDigits(int number) {
        long result = 0;
        int tmp = 1;
        while(number > 0) {
            tmp = number % 10;
           //recursive factorial method more details on here
            result += recfact_withoutstatic(tmp);
            number /= 10;
        }
        return (int)result;
    }
}

5. Check if the original input is equal to the sum


        if (i== addfactOfDigits (i))
       //i is the number we are passing to our function addfactOfDigits
            System.out.println(i);

«
Next
Newer Post
»
Previous
Older Post

No comments:

Leave a Reply