Guest User

Untitled

a guest
Jul 15th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. /*
  2. * Paweł Bogaczewicz
  3. * projecteuler.net
  4. * problem 20
  5. * Find the sum of the digits in the number 100!
  6. */
  7.  
  8. package org.bogaczew.euler.problems;
  9.  
  10. import java.math.BigInteger;
  11.  
  12. public class Euler020 {
  13.  
  14. /**
  15. * @param args
  16. */
  17. public static void main(String[] args) {
  18. System.out.println("projecteuler.net #020");
  19. System.out.println("Find the sum of the digits in the number 100!\n");
  20. int n = 20;
  21. if (args.length == 1) {
  22. try {
  23. n = Integer.parseInt(args[0]);
  24. } catch (Exception e) {
  25. System.out.println("arg parse error. will use default n=" + n
  26. + "\n\n");
  27. }
  28. }
  29. Euler020 euler = new Euler020();
  30. euler.sumDigits(euler.getFactorial(n).toString());
  31.  
  32. }
  33.  
  34. public BigInteger getFactorial(int n) {
  35. if (n < 0) {
  36. return BigInteger.ZERO;
  37. } else if (n > 0) {
  38. BigInteger factorial = BigInteger.ONE;
  39. for (int i = 1; i <= n; i++) {
  40. factorial = factorial.multiply(BigInteger.valueOf(i));
  41. }
  42. return factorial;
  43. } else {
  44. return BigInteger.ONE;
  45. }
  46. }
  47.  
  48. public void sumDigits(String s) {
  49. long sum = 0;
  50. for (int i = 0; i < s.length(); i++) {
  51. sum += Long.parseLong(s.substring(i, i + 1));
  52. System.out.print(s.charAt(i)+"|");
  53. }
  54. System.out.println("\n"+sum);
  55. }
  56. }
Add Comment
Please, Sign In to add comment