Perfect Number and Semi-Perfect Number (Ruby)


I wrote the code to check perfect number and semipefrect number in Ruby. Semiperfect number is also called pseudoperfect number.

Definition

Perfect Number
A positive integer that is equal to the sum of its proper positive divisors.
Semiperfect Number
A natural number n that is equal to the sum of all or some of its proper divisors.

Perfect number is also semiperfect number.

Code

Environment

  • Ruby 2.4.0

I created the class called Number. is_perfect? returns whether the number is perfect, is_semiperfect? returns whether the number is semi-perfect.

初期化処理のところで約数を配列に入れてしまっています。 初期化でそれをやるべきかというのは考えるべきことではありますが、今回は目的が特化しているのでこれで。

The first argument of check_semiperfect? is array whose member constructs subset sum. In this case, it only show whether perfect/semi-perfect or not, so it’s not used, but in outputting the sequence of elements which compose subset, it can be used.

We can use the above code as follows.

Its output is the following.

Supplementary

Semi-perfect number detection is called subset sum problem. (Reference: Programming Contest Challenge Book)