Project Euler #20: Factorial digit sum
Question
Answer : 648
Hacker Rank Problem
Solution
n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!
Answer : 648
Hacker Rank Problem
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import java.io.*; import java.util.*; import java.math.BigInteger; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner scanner= new Scanner(System.in); int T= scanner.nextInt(); for(int a0= 0; a0< T; a0++){ BigInteger N= scanner.nextBigInteger(); if(N.compareTo(BigInteger.valueOf(0))== 0){ System.out.println("1"); continue; } BigInteger sum= new BigInteger("0"); BigInteger fact= N; while(N.compareTo(BigInteger.valueOf(1))== 1){ fact= fact.multiply(N.subtract(BigInteger.valueOf(1))); N= N.subtract(BigInteger.valueOf(1)); } while(fact.compareTo(BigInteger.valueOf(0))== 1){ BigInteger temp= fact.mod(BigInteger.valueOf(10)); sum= sum.add(temp); fact= fact.divide(BigInteger.valueOf(10)); } System.out.println(sum); } } } |
Comments
Post a Comment