Advertisement
arkanon

findx

Aug 6th, 2015
341
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.07 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Arkanon <arkanon@lsd.org.br>
  4. # 2015/08/06 (Qui) 15:03:08 BRS
  5. #
  6. # <http://fb.com/PiMathAddicts/posts/391305147733661>
  7. # Puzzle by Aziz Inan, Professor of Electrical Engineering at the University of Portland
  8. #
  9. # Find the integer X that satisfies:
  10. #   1. the digits of X add up to a number Y where X equals Y times the number you get when you reverse the digits of Y.
  11. #   2. reverse the digits of X and find the prime factors of the number you get. Sum of the squares of these prime factors
  12. #      and halve it. Removing the digit 0 from the new number yields back X.
  13. #
  14. #      X    1729
  15. #      sdX  1+7+2+9+0
  16. #      Y    19
  17. #      rY   91
  18. #      YrY  1729
  19. #      rX   9271
  20. #      frX  73 127
  21. #      sfrX (73*73+ 127*127+0)/2
  22. #      S    10729
  23. #
  24. # Uma solução em BASh, executada serialmente e em paralelo com a última versão do Gnu Parallel (20150722) numa máquina
  25. #   com 1 processador i5 com 4 núcleos sem hyper-threading (não que esse problema exija muita capacidade computacional).
  26. #
  27. # Versão compacta:
  28. #
  29. #   findx()
  30. #   {
  31. #     local X=$1 Y=$(($(sed 's/./&+/g' <<< $X)0)) S
  32. #     S=$(( ( $(factor $(rev <<< $X) | cut -d: -f2 | sed -r 's/ [^ ]+/&*&+/g')0 ) / 2 ))
  33. #     ((X==Y*$(rev <<< $Y))) && tr -d 0 <<< $S | grep -q $X && echo $X $S || return 1
  34. #   }
  35. #
  36. # Versão human friendly:)
  37.  
  38.   findx()
  39.   {
  40.  
  41.     local X sdX Y rY YrY rX frX sfrX S
  42.  
  43.        X=$1
  44.      sdX=$(sed 's/./&+/g' <<< $X)0
  45.        Y=$((sdX))
  46.       rY=$(rev <<< $Y)
  47.      YrY=$((Y*rY))
  48.       rX=$(rev <<< $X)
  49.      frX=$(factor $rX | cut -d: -f2)
  50.     sfrX=($(sed -r 's/[^ ]+/&*&+/g' <<< $frX)0)/2
  51.        S=$((sfrX))
  52.  
  53.     ((X==YrY)) && tr -d 0 <<< $S | grep -q $X \
  54.                                    && echo -e "X\t$X\nsdX\t$sdX\nY\t$Y\nrY\t$rY\nYrY\t$YrY\nrX\t$rX\nfrX\t$frX\nsfrX\t$sfrX\nS\t$S" \
  55.                                    || return 1
  56.  
  57.   }
  58.  
  59.   export -f findx
  60.  
  61.   time ( TIMEFORMAT=%lR; x=0; while ! findx $x; do ((x++)); done )
  62.   # 0m18.281s
  63.  
  64.   time ( TIMEFORMAT=%lR; seq 1000000 | parallel --no-notice --halt now,success=1 findx 2> /dev/null )
  65.   # 0m9.156s
  66.  
  67. # EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement