How to resolve the algorithm Self numbers step by step in the Standard ML programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Self numbers step by step in the Standard ML programming language

Table of Contents

Problem Statement

A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.

The task is: 224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Self numbers step by step in the Standard ML programming language

Source code in the standard programming language

open List;

val rec selfNumberNr = fn NR =>
let
  val rec sumdgt = fn 0 => 0 | n => Int.rem (n, 10) + sumdgt (Int.quot(n ,10));
  val rec isSelf  = fn ([],l1,l2) => []
   | (x::tt,l1,l2) => if exists (fn i=>i=x) l1 orelse exists (fn i=>i=x) l2
			  then ( isSelf (tt,l1,l2)) else x::isSelf (tt,l1,l2) ;

  val rec partcount =  fn  (n, listIn , count , selfs) =>
         if count >= NR then  nth (selfs, length selfs + NR - count -1)
           else
         let
          val range   = tabulate (81 , fn i => 81*n +i+1) ;
          val listOut = map (fn i => i + sumdgt i ) range ;
          val selfs   = isSelf (range,listIn,listOut)
         in
          partcount ( n+1 , listOut , count+length (selfs) , selfs )
       end;
in
  partcount (0,[],0,[])
end;

app  ((fn s => print (s ^ " ")) o Int.toString o selfNumberNr)  (tabulate (50,fn i=>i+1)) ;
selfNumberNr 100000000 ;


  

You may also check:How to resolve the algorithm Pig the dice game step by step in the REXX programming language
You may also check:How to resolve the algorithm Sorting algorithms/Cocktail sort with shifting bounds step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Loops/For step by step in the Alore programming language
You may also check:How to resolve the algorithm Loop over multiple arrays simultaneously step by step in the Fantom programming language
You may also check:How to resolve the algorithm Loops/For step by step in the NetRexx programming language