prime_recursive_representation.sf 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/ruby
  2. # Represent a given prime using only 2s and 1s, recursively using its P +/- 1 factorization.
  3. func pminus1_representation(p) {
  4. return "2" if (p == 2)
  5. '(' + (p-1 -> factor_map{|p,e|
  6. var t = __FUNC__(p)
  7. e == 1 ? t : "#{t}^#{e}"
  8. }.join(' * ')) + ' + 1)'
  9. }
  10. func pplus1_representation(p) {
  11. return "2" if (p == 2)
  12. '(' + (p+1 -> factor_map{|p,e|
  13. var t = __FUNC__(p)
  14. e == 1 ? t : "#{t}^#{e}"
  15. }.join(' * ')) + ' - 1)'
  16. }
  17. say "=> P-1 representation:"
  18. say pminus1_representation(59649589127497217)
  19. say "\n=> P+1 representation:"
  20. say pplus1_representation(59649589127497217)
  21. __END__
  22. => P-1 representation:
  23. (2^9 * (2 * (2 * (2 + 1) + 1) * (2^6 * (2 * (2 + 1) + 1) + 1) * (2 * (2 + 1)^3 * (2^2 * (2 + 1)^2 * (2^2 + 1) + 1) * (2^2 * (2 + 1)^2 * (2^6 * (2 * (2 + 1) * (2^3 * (2^4 + 1) + 1) + 1) + 1) + 1) + 1) + 1) + 1)
  24. => P+1 representation:
  25. (2 * (2^2 - 1) * (2 * (2^4 * (2^3 * (2^2 - 1) - 1) - 1) - 1) * (2^3 * (2^5 - 1) * (2^4 * (2^2 - 1) * (2^3 - 1) * (2 * (2^2 - 1) * (2^2 * (2 * (2^2 - 1) - 1) - 1) - 1) - 1) * (2 * (2^2 - 1) * (2 * (2 * (2^2 - 1)^2 - 1) * (2^3 * (2^2 - 1) - 1) * (2^2 * (2^3 - 1) * (2^2 * (2^2 - 1) - 1) - 1) - 1) - 1) - 1) - 1)