DEV Community

Discussion on: Write a script to find "Happy Numbers"

Collapse
 
jacoby profile image
Dave Jacoby

A work in two parts. First, Happy.pm, a Perl5 Module.

package Happy ;

use strict ;
use warnings ;
use utf8 ;
use feature qw{ postderef say signatures state } ;
no warnings qw{ experimental::postderef experimental::signatures } ;

use Carp ;
use Exporter qw( import ) ;
use List::Util qw( sum0 ) ;

our @EXPORT = qw( is_happy ) ;
our %EXPORT_TAGS = ( 'all' => [ @EXPORT ], ) ;
our @EXPORT_OK = ( @{ $EXPORT_TAGS{ 'all' } } ) ;
our $VERSION = 0.0.1 ;

sub is_happy ( $number ) {
    croak 'Not a number' if $number =~ m{\D} ;
    croak 'Not anything' if !defined $number ;
    my %done ;
    while ( $number != 0 && $number != 1 ) {
        return 0 if $done{ $number } ;
        my $output = sum0 map { $_ ** 2 } split m{}, $number ;
        $done{ $number } = $output ;
        $number = $output ;
        }
    return $number ;
    }
1 ;

Which is called by a program.

#!/usr/bin/env perl

use strict ;
use warnings ;
use utf8 ;
use feature qw{ say } ;

use lib '/home/jacoby/lib' ;
use Happy ;

for my $i ( 0 .. 1_000_000 ) {
    say $i if is_happy( $i ) ;
    }

Not particularly golfy, because I like reading and understanding things.