palindromes.hs 918 B

12345678910111213141516171819202122232425
  1. -- Author: estelendur
  2. -- Given a base b and a number of digits n, how many palindromic integers?
  3. -- What proportion of possible integers are palindromes?
  4. -- Can we learn anything interesting from this?
  5. --half :: (Integral a) => a -> a
  6. --half x = ceiling(x/2)
  7. --pals :: (Integral a) => a -> a -> a
  8. pals n b = (b-1)*(b^(ceiling((n-1)/2))
  9. --num :: (Integral a) => a -> a -> a
  10. num n b = (b-1)*(b^(n-1))
  11. prop :: (Integral a) => a -> a -> Double
  12. prop n b = (pals n b)/(num n b)
  13. -- Find out the proportion of palindromes for all n, b up to nm, bm
  14. test :: (Integral a) => a -> a -> String
  15. test 1 1 = "1 digit in base 1 gives 1 palindrome\n"
  16. test n 1 = n ++ " digits in base 1 gives 1 palindrome\n"
  17. test 1 b = "1 digit in base " ++ b ++ " gives " ++ (b-1) ++ " palindromes\n"
  18. test nm bm = nm ++ " digits in base " ++ bm ++ " gives " ++ (prop nm bm)*100 ++ " percent palindromes\n" ++ (test (nm-1) bm) ++ (test nm (bm-1))