Guest User

Euler #4

a guest
Jul 14th, 2012
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <ctime>
  2. #include <iostream>
  3. #include <algorithm>
  4.  
  5. typedef unsigned long long main_type;
  6.  
  7. main_type evaluated=0,
  8.     is_palindrome_called=0;
  9.  
  10. bool is_palindrome(main_type n){
  11.     is_palindrome_called++;
  12.     if (!n)
  13.         return 1;
  14.     char digits[100]={0};
  15.     size_t s=0;
  16.     while (n){
  17.         digits[s++]=n%10;
  18.         n/=10;
  19.     }
  20.     if (s<3)
  21.         return 1;
  22.     //reusing n:
  23.     n=s/2+s%2;
  24.     for (size_t a=0;a<n;a++)
  25.         if (digits[a]!=digits[s-a-1])
  26.             return 0;
  27.     return 1;
  28. }
  29.  
  30. struct result_t{
  31.     main_type candidate,x,y;
  32. };
  33.  
  34. #define N 999
  35.  
  36. result_t get(){
  37.     bool found=0;
  38.     result_t result;
  39.     for (main_type x=N;x>99;x--){
  40.         main_type end=99;
  41.         if (found)
  42.             end=result.candidate/x;
  43.         if (end>=N)
  44.             break;
  45.         for (main_type y=N;y>end && y>=x;y--){
  46.             evaluated++;
  47.             if (found && x*y<=result.candidate)
  48.                 continue;
  49.             if (!is_palindrome(x*y))
  50.                 continue;
  51.             if (!found || x*y>result.candidate){
  52.                 result.candidate=x*y;
  53.                 result.x=x;
  54.                 result.y=y;
  55.                 found=1;
  56.                 break;
  57.             }
  58.         }
  59.     }
  60.     return result;
  61. }
  62.  
  63. int main(){
  64.     result_t r;
  65.     clock_t t0=clock();
  66.     const unsigned repeats=1000;
  67.     main_type max_evaluated=0,
  68.         max_is_palindrome_called=0;
  69.     for (unsigned a=0;a<repeats;a++){
  70.         r=get();
  71.         max_evaluated=std::max(max_evaluated,evaluated);
  72.         evaluated=0;
  73.         max_is_palindrome_called=std::max(max_is_palindrome_called,is_palindrome_called);
  74.         is_palindrome_called=0;
  75.     }
  76.     clock_t t1=clock();
  77.     std::cout <<r.candidate<<std::endl;
  78.     std::cout <<max_evaluated<<std::endl;
  79.     std::cout <<max_is_palindrome_called<<std::endl;
  80.     std::cout <<double(t1-t0)/repeats<<std::endl;
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment