fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. class ADG {
  6. public static void main(String[] args) throws java.lang.Exception {
  7. int totalPages = 411;
  8. int expectedDays = 6;
  9. for (int firstDay = 1; firstDay <= totalPages; firstDay++) {
  10. Stack<Integer> solution = checkSolution(0, firstDay, totalPages);
  11. if (solution != null && solution.size() == expectedDays) {
  12. printSolution(solution);
  13. }
  14. }
  15. }
  16.  
  17. private static void printSolution(Stack<Integer> solution) {
  18. int i = 1;
  19. while (!solution.empty()) {
  20. int pages = solution.pop();
  21. System.out.println("Day " + i + " " + pages + " pages");
  22. i++;
  23. }
  24. }
  25.  
  26. private static Stack<Integer> checkSolution(int soFar, int current, int total) {
  27. int totalRead = soFar + current;
  28.  
  29. if (totalRead == total) {
  30. // reached the total
  31. Stack<Integer> solution = new Stack<Integer>();
  32. solution.push(current);
  33. return solution;
  34. }
  35. if (totalRead > total) {
  36. // already passed total
  37. return null;
  38. }
  39.  
  40. // see if this leads to a solution
  41. Stack<Integer> solution = checkSolution(totalRead, squareOfDigitSum(totalRead), total);
  42.  
  43. if (solution == null) {
  44. // doesn't lead to a solution
  45. return solution;
  46. }
  47.  
  48. solution.push(current);
  49. return solution;
  50. }
  51.  
  52. public static int squareOfDigitSum(int pNum) {
  53. int total = 0;
  54. while (pNum > 0) {
  55. total += pNum % 10;
  56. pNum /= 10;
  57. }
  58. return (total * total);
  59. }
  60.  
  61. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
Day 1 61 pages
Day 2 49 pages
Day 3 4 pages
Day 4 36 pages
Day 5 36 pages
Day 6 225 pages