# by bliako on 30/08/2021 # for https://perlmonks.org/?node_id=11136212 use bigint qw/hex/; use Digest::SHA1 qw/sha1 sha1_hex/; my \$digest_hex = sha1_hex('blah blah blah'); my \$answer = hex(\$digest_hex); print "\$0 : starting with this number: \$answer.\n"; my \$min = 0; my \$max = 2**160; my \$num_guesses = 0; my (\$guess, \$diff); while( ++\$num_guesses ){ \$guess = \$min + (\$max - \$min) / 2.0; \$diff = \$guess - \$answer; print "entering at guess number \$num_guesses, current range:\n min: \$min\n max: \$max\n answer: \$answer\n guess: \$guess\n diff: \$diff\n"; if( \$guess < \$answer ){ print "your guess (\$guess) needs to go higher ...\n"; \$min = int(\$guess); } elsif( \$guess > \$answer ){ print "your guess (\$guess) needs to go lower ...\n"; \$max = int(\$guess); } else { print "bingo in \$num_guesses guesses! the answer was: \$digest_hex and your guess was ".bigint_to_hex(\$guess)." (\$guess).\n"; last; } } sub bigint_to_hex { # graduitously ripped off from Ben Aveling's answer in # https://stackoverflow.com/questions/828462/how-can-i-sprintf-a-big-number-in-perl # because sprintf("%x", bigint) does not work sadly... my \$inp = shift; my \$out = ""; while(\$inp){ my \$chunk=\$inp & 0xf; \$inp >>= 4; \$out = sprintf("%x",\$chunk).\$out; } return \$out; } ##```## entering at guess number XXX, current range: min: 216530321997656745029789011476757518019484653536 max: 216530321997656745029789011476757518019484653568 answer: 216530321997656745029789011476757518019484653552 guess: 216530321997656745029789011476757518019484653552 diff: 0 bingo in XXX guesses! the answer was: 25ed8e31b995bb927966616df2a42b979a2717f0 and your guess was 25ed8e31b995bb927966616df2a42b979a2717f0 (216530321997656745029789011476757518019484653552). ```