How to resolve the algorithm Perfect numbers step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Perfect numbers step by step in the D programming language

Table of Contents

Problem Statement

Write a function which says whether a number is perfect.

A perfect number is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself).

Note:   The faster   Lucas-Lehmer test   is used to find primes of the form   2n-1,   all known perfect numbers can be derived from these primes using the formula   (2n - 1) × 2n - 1. It is not known if there are any odd perfect numbers (any that exist are larger than 102000). The number of   known   perfect numbers is   51   (as of December, 2018),   and the largest known perfect number contains  49,724,095  decimal digits.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Perfect numbers step by step in the D programming language

Source code in the d programming language

import std.stdio, std.algorithm, std.range;

bool isPerfectNumber1(in uint n) pure nothrow
in {
    assert(n > 0);
} body {
    return n == iota(1, n - 1).filter!(i => n % i == 0).sum;
}

void main() {
    iota(1, 10_000).filter!isPerfectNumber1.writeln;
}


import std.stdio, std.math, std.range, std.algorithm;

bool isPerfectNumber2(in int n) pure nothrow {
    if (n < 2)
        return false;

    int total = 1;
    foreach (immutable i; 2 .. cast(int)real(n).sqrt + 1)
        if (n % i == 0) {
            immutable int q = n / i;
            total += i;
            if (q > i)
                total += q;
        }

    return total == n;
}

void main() {
    10_000.iota.filter!isPerfectNumber2.writeln;
}


  

You may also check:How to resolve the algorithm Bitmap/Bresenham's line algorithm step by step in the E programming language
You may also check:How to resolve the algorithm Here document step by step in the SQL PL programming language
You may also check:How to resolve the algorithm Fibonacci word step by step in the REXX programming language
You may also check:How to resolve the algorithm FizzBuzz step by step in the ECL programming language
You may also check:How to resolve the algorithm Morse code step by step in the OCaml programming language