How to resolve the algorithm Abundant, deficient and perfect number classifications step by step in the Picat 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 Picat 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 Picat programming language

Source code in the picat programming language

go =>  
  Classes = new_map([deficient=0,perfect=0,abundant=0]),
  foreach(N in 1..20_000)
    C = classify(N),
    Classes.put(C,Classes.get(C)+1)
  end,
  println(Classes),
  nl.

% Classify a number N
classify(N) = Class =>
 S = sum_divisors(N),
 if S < N then 
   Class1 = deficient
 elseif S = N then 
   Class1 = perfect
 elseif S > N then
   Class1 = abundant
 end,
 Class = Class1.

% Alternative (slightly slower) approach.
classify2(N,S) = C, S <  N => C = deficient.
classify2(N,S) = C, S == N => C = perfect.
classify2(N,S) = C, S >  N => C = abundant.

% Sum of divisors
sum_divisors(N) = Sum =>
  sum_divisors(2,N,cond(N>1,1,0),Sum).

% Part 0: base case
sum_divisors(I,N,Sum0,Sum), I > floor(sqrt(N)) =>
  Sum = Sum0.

% Part 1: I is a divisor of N
sum_divisors(I,N,Sum0,Sum), N mod I == 0 =>
  Sum1 = Sum0 + I,
  (I != N div I -> 
    Sum2 = Sum1 + N div I 
    ; 
    Sum2 = Sum1
  ),
  sum_divisors(I+1,N,Sum2,Sum).

% Part 2: I is not a divisor of N.
sum_divisors(I,N,Sum0,Sum) =>
  sum_divisors(I+1,N,Sum0,Sum).

  

You may also check:How to resolve the algorithm Harshad or Niven series step by step in the Phix programming language
You may also check:How to resolve the algorithm Abstract type step by step in the D programming language
You may also check:How to resolve the algorithm Loops/For with a specified step step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm Forest fire step by step in the uBasic/4tH programming language
You may also check:How to resolve the algorithm Update a configuration file step by step in the Delphi programming language