#!/usr/bin/ruby # solves A = x + B^x (uint32_t, no overflows) a = Integer(ARGV.shift) b = Integer(ARGV.shift) def solve(a, b) x = 0 carry = 0 # per bit truth table, c = carry # c A B x c # 0 0 0 0 0 # 0 1 0 0 1 # 1 0 0 1 0 # 1 1 0 1 1 # 0 1 1 0 0 # 1 0 1 0 1 # 0 1 1 1 0 # 1 0 1 1 1 # reordered # c A B x c # 0 0 0 0 0 # 0 1 0 0 1 # 0 1 1 1 0 # 0 1 1 0 0 # 1 0 0 1 0 # 1 0 1 0 1 # 1 0 1 1 1 # 1 1 0 1 1 bit = lambda { |var, off| (var >> off) & 1 } 31.downto(0) { |i| case [carry, bit[a, i], bit[b, i]] when [0, 0, 0] #x |= 1 << i carry = 0 when [0, 0, 1] raise when [0, 1, 0] #x |= 1 << i carry = 1 when [0, 1, 1] puts 'rand' x |= 1 << i if rand(2) == 0 carry = 0 when [1, 0, 0] x |= 1 << i carry = 0 when [1, 0, 1] puts 'rand' x |= 1 << i if rand(2) == 0 carry = 1 when [1, 1, 0] x |= 1 << i carry = 1 when [1, 1, 1] raise end } raise if carry == 1 x rescue abort "no solution for #{a} = x + #{b}^x" end x = solve(a, b) puts "#{a} = x + #{b}^x <= x=#{x}"