The Weekly Challenge 006

Compact Numbers and Ramanujan's Constant

Solutions on GitHub

Task 1: Compact number lists

Takes a list of numbers from the command line and prints them in compact form. For example, passing 1,2,3,4,9,10,14,15,16 outputs 1-4,9,10,14-16.

Example Output

Input: 1,2,3,4,9,10,14,15,16 Output: 1-4,9,10,14-16

Logic

Sort the numbers in ascending order. Traverse the array tracking continuous intervals. If an interval has length 3 or greater (end - start >= 2), format it as start-end; if it has length 2, format as start,end; otherwise format as a single number.

Perl Solution

ch-1.pl

sub compact_number_list (@numbers) { return '' if !@numbers; my @sorted = sort { $a <=> $b } @numbers; my @compact; my $start = $sorted[0]; my $end = $sorted[0]; my sub append_range ( $s, $e ) { if ( $e - $s >= 2 ) { push @compact, "$s-$e"; } elsif ( $e - $s == 1 ) { push @compact, $s, $e; } else { push @compact, "$s"; } } for my $num ( @sorted[ 1 .. $#sorted ] ) { if ( $num == $end + 1 ) { $end = $num; } elsif ( $num == $end ) { next; } else { append_range( $start, $end ); $start = $num; $end = $num; } } append_range( $start, $end ); return join( ',', @compact ); }

Python Solution

ch-1.py

def compact_number_list(numbers: list[int]) -> str: """Compact a list of integers into ranges.""" if not numbers: return "" sorted_nums = sorted(numbers) compact: list[str] = [] start = sorted_nums[0] end = sorted_nums[0] def append_range(s: int, e: int) -> None: if e - s >= 2: compact.append(f"{s}-{e}") elif e - s == 1: compact.extend([str(s), str(e)]) else: compact.append(str(s)) for num in sorted_nums[1:]: if num == end + 1: end = num elif num == end: continue else: append_range(start, end) start = end = num append_range(start, end) return ",".join(compact)

Task 2: Ramanujan's constant

Calculate Ramanujan's constant: e^(pi * sqrt(163)) with at least 32 digits of precision.

Example Output

Output: 262537412640768743.999999999999250072597...

Logic

Ramanujan's constant produces an "almost integer" that requires arbitrary-precision floating-point arithmetic beyond standard IEEE 754 float:

Perl Solution

ch-2.pl

sub ramanujan_constant ($digits = 35) { Math::BigFloat->accuracy( $digits + 10 ); my $pi = Math::BigFloat->bpi( $digits + 10 ); my $sqrt_163 = Math::BigFloat->new(163)->bsqrt(); my $exponent = $pi->bmul($sqrt_163); my $constant = $exponent->bexp(); $constant->accuracy($digits); return $constant->bstr(); }

Python Solution

ch-2.py

def ramanujan_constant(prec: int = 35) -> str: """Calculate Ramanujan's constant: e^(pi * sqrt(163)).""" getcontext().prec = prec + 10 pi_val = pi(prec + 10) sqrt_163 = Decimal(163).sqrt() exponent = pi_val * sqrt_163 getcontext().prec = prec result = exp_value(exponent, prec) return str(result)