fork download
  1. class ProjectEulerQ04 {
  2. private static int reverse(int n){
  3. int reversed = 0;
  4. while(n>0){
  5. reversed *= 10;
  6. reversed += n%10;
  7. n /= 10;
  8. }
  9. return reversed;
  10. }
  11. public static void method1(){
  12. //checks x*y where 1<x<=y<=999
  13. int max=0;
  14. int candidate;
  15. for(int x=1;x<=999;x++){
  16. for(int y=x;y<=999;y++){
  17. candidate = x*y;
  18. if(candidate == reverse(candidate)){
  19. if(candidate > max){
  20. max = candidate;
  21. }
  22. }
  23. }
  24. }
  25. System.out.println("Output: "+max);
  26. }
  27. public static void method2(){
  28. //builds table of x*y, where 1 < y <= x <= 999
  29. boolean[] is_product = new boolean[1000000];
  30. for(int x=1;x<=999;x++){
  31. for(int y=1;y<=x;y++){
  32. is_product[x*y] = true;
  33. }
  34. }
  35. //checks all palindromes
  36. int max = 0;
  37. int power = 1;
  38. int temp1,temp2;
  39. for(int i=1;i<=999;i++){
  40. if(reverse(i) == 1){
  41. power *= 10;
  42. }
  43. temp1 = (i/10)*(power)+reverse(i);
  44. temp2 = i*(power)+reverse(i);
  45. if(is_product[temp1]){
  46. if(temp1 > max){
  47. max = temp1;
  48. }
  49. }
  50. if(is_product[temp2]){
  51. if(temp2 > max){
  52. max = temp2;
  53. }
  54. }
  55. }
  56. System.out.println("Output: "+max);
  57. }
  58. public static void main(String args[]){
  59. long start;
  60.  
  61. System.out.println("Solve by checking each product:");
  62. start = System.currentTimeMillis();
  63. method1();
  64. System.out.println("Time used: "+(System.currentTimeMillis()-start)+" ms");
  65.  
  66. System.out.println();
  67.  
  68. System.out.println("Solve by checking each palindrome:");
  69. start = System.currentTimeMillis();
  70. method2();
  71. System.out.println("Time used: "+(System.currentTimeMillis()-start)+" ms");
  72. }
  73. }
Success #stdin #stdout 0.21s 320512KB
stdin
Standard input is empty
stdout
Solve by checking each product:
Output: 906609
Time used: 102 ms

Solve by checking each palindrome:
Output: 906609
Time used: 6 ms