How to resolve the algorithm Happy numbers step by step in the Maple programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Happy numbers step by step in the Maple programming language

Table of Contents

Problem Statement

From Wikipedia, the free encyclopedia:

Find and print the first   8   happy numbers. Display an example of your output here on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Happy numbers step by step in the Maple programming language

Source code in the maple programming language

SumSqDigits := proc( n :: posint )
        local s := 0;
        local m := n;
        while m <> 0 do
                s := s + irem( m, 10, 'm' )^2
        end do;
        s
end proc:

> SumSqDigits( 1234567890987654321 );
                                  570

> n := 1234567890987654321:
> `+`( op( map( parse, StringTools:-Explode( convert( n, 'string' ) ) )^~2) );
                                  570

Happy? := proc( n )
        if n = 1 then
                true
        elif n = 4 then
                false
        else
                local s := SumSqDigits( n );
                while not ( s in { 1, 4 } ) do
                        s := SumSqDigits( s )
                end do;
                evalb( s = 1 )
        end if
end proc:

> H, S := selectremove( Happy?, [seq]( 1 .. N ) ):
> nops( H ), nops( S );
                             143071, 856929

FindHappiness := proc( N )
        local count := 0;
        local T := table();
        for local i while count < N do
                if Happy?( i ) then
                        count := 1 + count;
                        T[ count ] := i
                end if
        end do;
        {seq}( T[ i ], i = 1 .. count )
end proc:

> FindHappiness( 8 );
                     {1, 7, 10, 13, 19, 23, 28, 31}

Happy? := proc( n :: posint )
        local a, b;
        a, b := n, SumSqDigits( n );
        while a <> b do
                a := SumSqDigits( a );
                b := (SumSqDigits@@2)( b )
        end do;
        evalb( a = 1 )
end proc:

  

You may also check:How to resolve the algorithm General FizzBuzz step by step in the zkl programming language
You may also check:How to resolve the algorithm Window creation step by step in the Oz programming language
You may also check:How to resolve the algorithm Archimedean spiral step by step in the Processing programming language
You may also check:How to resolve the algorithm Short-circuit evaluation step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Plasma effect step by step in the Phix programming language