N = gets.to_i D = N.to_s.size def f(n) return false if n <= 0 return false if n % 3 != 0 digits = n.digits return false if digits.size <= 1 digits.combination(2).all? { |a, b| (a + b) % 3 == 0 } end ans = 0 (1..[N, 99].min).each do |n| ans += 1 if f(n) end $cnt = 0 $checked = Hash.new(false) def dfs(sum, base, depth) return if D < depth if depth >= 3 && 100 <= sum && sum <= N && !$checked[sum] $checked[sum] = true $cnt += 1 end [0, 3, 6, 9].each do |n| s = sum + base * n dfs(s, base * 10, depth + 1) end end dfs(0, 1, 0) puts $cnt + ans