#!/usr/bin/env ruby # -*- ruby -*- # # Public Domain -- Christian Neukirchen 2001 # # Prove the theorem: # Add a number to it's reverse unless the sum is ``symetric''. # That should be possible for all numbers. # # Examples: # 1) # 34 + 43 = 77; # So 34 is ok. # # 2) # 546 + 645 = 1191 # 1191 + 1911 = 3102 # 3102 + 2013 = 5115; # So 546 is ok. # # # Try 196 ;-) [Hint: It needs more than 10000 steps (!)] # # Is 's' symetric? # Examples: # symetric?('6565') => false # symetric?('7465') => false # symetric?('5665') => true # symetric?('898') => true def symetric? (str) 0.upto ((str.length-1) / 2) { |i| # `i' is the iterator return false if str[i] != str[-i-1] } true # else return true end if ARGV[0].to_i != 0 num = ARGV[0].to_i # Take the number from the command line. else num = (rand * 100000).round # If none given, use a random one. end print "The number ", num, ":\n" cnt = 0 res = num while (!symetric? res.to_s) cnt += 1 # Increase the # of steps. printf "[%4d]\n ", cnt rev = num.to_s.reverse # print num, " + ", rev, " = " res = num + rev.to_i num = res # printf "%d\t(Step %4d)\n", res, cnt end print res print "is ok (", cnt, " steps, len = ", num.to_s.length, ")\n"