Skip to content

Instantly share code, notes, and snippets.

@hyuki
Last active March 25, 2018 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hyuki/90b40e37cb6a5a2d049a78db8d1d2376 to your computer and use it in GitHub Desktop.
Save hyuki/90b40e37cb6a5a2d049a78db8d1d2376 to your computer and use it in GitHub Desktop.
def sqsum(x)
y = 0
x.to_s.split(//).each do |s|
a = s.to_i
y += a ** 2
end
y
end
def seq_sqsum(x)
h = {}
while not h[x]
print "#{x} -> "
h[x] = true
x = sqsum(x)
end
puts "#{x} -> ..."
end
seq_sqsum(4)
seq_sqsum(1000)
seq_sqsum(3)
seq_sqsum(31)
seq_sqsum(314)
seq_sqsum(3141)
seq_sqsum(31415)
seq_sqsum(314159)
seq_sqsum(3141592)
seq_sqsum(31415926)
seq_sqsum(314159265)
@hyuki
Copy link
Author

hyuki commented Mar 25, 2018

4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> ...
1000 -> 1 -> 1 -> ...
3 -> 9 -> 81 -> 65 -> 61 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> ...
31 -> 10 -> 1 -> 1 -> ...
314 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> ...
3141 -> 27 -> 53 -> 34 -> 25 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 -> ...
31415 -> 52 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 -> ...
314159 -> 133 -> 19 -> 82 -> 68 -> 100 -> 1 -> 1 -> ...
3141592 -> 137 -> 59 -> 106 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> ...
31415926 -> 173 -> 59 -> 106 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> ...
314159265 -> 198 -> 146 -> 53 -> 34 -> 25 -> 29 -> 85 -> 89 -> 145 -> 42 -> 20 -> 4 -> 16 -> 37 -> 58 -> 89 -> ...

@hyuki
Copy link
Author

hyuki commented Mar 25, 2018

“任意の正整数から始め、その数を構成している各桁の数字を平方して足し合わせる操作を繰り返せ。すると必ず、1になって終わるか、8個の数をぐるぐる回るかのいずれかになる”
https://www.johndcook.com/blog/2018/03/24/squared-digit-sum/

@hyuki
Copy link
Author

hyuki commented Mar 25, 2018

def sqsum(x)
  x.to_s.split(//).map { |d| d.to_i ** 2 }.reduce(0) { |sum, sq| sum += sq }
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment