Advertisement
shardy

Factorial_Total_Digit_Sum

Sep 30th, 2012
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.80 KB | None | 0 0
  1. package java20;
  2.  
  3. /**
  4.  * Program to calculate the factorial of a given number.
  5.  * Once implemented, it will calculate how many digits the answer includes.
  6.  * It will then sum these digits together to provide a total.
  7.  * @author shardy
  8.  * date: 30/09/2012
  9.  */
  10.  
  11. //import java.math.BigInteger;
  12. public class Java20 {
  13.  
  14.     /**
  15.      * @param args the command line arguments
  16.      */
  17.     public static void main(String[] args) {
  18.        
  19.         //Using given number stored in factorialNo, calculates factorial
  20.         //currently only works for numbers between 1! and 31! :(
  21.             int fact= 1;
  22.             int factorialNo = 10;
  23.  
  24.             for (int i = 1; i <= factorialNo; i++)
  25.                 {
  26.                    fact=fact*i;
  27.                 }
  28.  
  29.             System.out.println("The factorial of " + factorialNo +
  30.                     " (or " + factorialNo + "!) is: " + fact);
  31.            
  32.             //Using answer stored in fact, calculates how many digits the answer has
  33.             final int answerNo = fact;
  34.             final int digits = 1 + (int)Math.floor(Math.log10(answerNo));
  35.  
  36.             System.out.println("The number of digits in the factorials "
  37.                     + "answer is: " + digits);        
  38.            
  39.             //Using remainders, calculates each digits value and sums them together
  40.             int number = fact;
  41.             int reminder;
  42.             int sum = 0;
  43.  
  44.             while(number>=1)
  45.                 {
  46.                  reminder=number%10;
  47.                  sum=sum+reminder;
  48.                  number=number/10;
  49.                 }
  50.  
  51.             System.out.println("The total sum of all the " + digits
  52.                     + " idividual digits from the answer of the factorial of "
  53.                     + factorialNo + " is: " + sum);
  54.        
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement