The Weekly Challenge 016

Pythagoras Pie Puzzle and Bitcoin Address Validation

Solutions on GitHub

Task 1: Pythagoras Pie Puzzle

At a party a pie is to be shared by 100 guest. The first guest gets 1% of the pie, the second guest gets 2% of the remaining pie, the third gets 3% of the remaining pie, and so on. Write a script that figures out which guest gets the largest piece of pie.

Output

Guest 10 gets the largest piece: 6.28%

Logic

Simulate the process of guest consumption. Start with 100% of the pie. For each guest $i \in [1, 100]$, compute the portion $P_i = \text{remaining} \times \frac{i}{100}$, check if this portion is larger than the previous maximum portion, update the maximum, and subtract the portion from the remaining pie.

Perl Solution

ch-1.pl

my $pie_left = 1; my $max_portion = 0; sub get_portion { my ($pie, $n) = @_; return $pie * $n / 100; } for my $n (1..100) { my $portion = get_portion( $pie_left, $n ); if ( $portion < $max_portion ) { $n--; say 'Biggest portion has guest '. $n .' , portion size '.sprintf("%.2f%%\n",$max_portion*100); last; } $max_portion = $portion; $pie_left -= $portion; }

Python Solution

ch-1.py

def pythagoras_pie(num_guests: int = 100) -> tuple[int, float]: remaining = 100.0 largest_piece = 0.0 largest_guest = 0 for guest in range(1, num_guests + 1): piece = (guest / 100) * remaining if piece > largest_piece: largest_piece = piece largest_guest = guest remaining = remaining - piece return largest_guest, largest_piece

Task 2: Bitcoin Address Validation

Write a script to validate a given bitcoin address. A valid address must be 26-35 characters, use only Base58 characters (excluding 0, O, I, l), and have a matching checksum calculated from double SHA-256 hash of the payload bytes.

Example

1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2 -> Valid

Logic

Validate formatting rules (length and character set). Decode the Base58 string into bytes. Extract the payload (first 21 bytes) and the checksum (last 4 bytes). Perform double SHA-256 hashing on the payload and compare the first 4 bytes of the hash to the checksum.

Perl Solution

ch-2.pl

use WWW::Mechanize; sub is_valid_bitcoin { my $test_id = shift; my $mech = WWW::Mechanize->new; $mech->get( 'https://cointools.org/valid-address-checker/?address=' . $test_id ); return 'valid' if $mech->content =~ /is\h+a\h+valid\h+bitcoin\h+address/msx; return 'invalid'; }

Python Solution

ch-2.py

import hashlib BASE58_CHARS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" def validate_bitcoin_address(address: str) -> bool: if len(address) < 26 or len(address) > 35: return False if any(c in "0OIl" for c in address): return False try: decoded = decode_base58(address, 25) except ValueError: return False checksum = decoded[-4:] payload = decoded[:21] hash1 = hashlib.sha256(payload).digest() hash2 = hashlib.sha256(hash1).digest() return hash2[:4] == checksum