How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the Forth programming language

Table of Contents

Problem Statement

These define three classifications of positive integers based on their   proper divisors. Let   P(n)   be the sum of the proper divisors of   n   where the proper divisors are all positive divisors of   n   other than   n   itself.

6   has proper divisors of   1,   2,   and   3. 1 + 2 + 3 = 6,   so   6   is classed as a perfect number.

Calculate how many of the integers   1   to   20,000   (inclusive) are in each of the three classes. Show the results here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the Forth programming language

Source code in the forth programming language

CREATE A 0 ,
: SLOT ( x y -- 0|1|2)  OVER OVER < -ROT > -  1+ ;
: CLASSIFY ( n -- n')  \ 0 == deficient, 1 == perfect, 2 == abundant
   DUP A !  \ we'll be accessing this often, so save somewhere convenient
   2 / >R   \ upper bound
   1        \ starting sum, 1 is always a divisor
   2        \ current check
   BEGIN DUP R@ < WHILE
     A @ OVER /MOD SWAP ( s c d m)
     IF DROP ELSE
       R> DROP DUP >R  ( R: d n)
       OVER TUCK OVER <> * -  ( s c c+?d)
       ROT + SWAP ( s' c)
     THEN 1+
   REPEAT  DROP R> DROP A @  ( sum n)  SLOT ; 
CREATE COUNTS 0 , 0 , 0 ,
: INIT   COUNTS 3 CELLS ERASE  1 COUNTS ! ;
: CLASSIFY-NUMBERS ( n --)  INIT
   BEGIN DUP WHILE 
     1 OVER CLASSIFY  CELLS COUNTS + +!  1-
   REPEAT  DROP ;
: .COUNTS
   ." Deficient : " [ COUNTS ]L           @ . CR
   ." Perfect   : " [ COUNTS 1 CELLS + ]L @ . CR
   ." Abundant  : " [ COUNTS 2 CELLS + ]L @ . CR ;
20000 CLASSIFY-NUMBERS .COUNTS BYE


  

You may also check:How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Metafont programming language
You may also check:How to resolve the algorithm Same fringe step by step in the J programming language
You may also check:How to resolve the algorithm Phrase reversals step by step in the Quackery programming language
You may also check:How to resolve the algorithm DNS query step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm Plasma effect step by step in the Delphi programming language