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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Perfect numbers step by step in the Zig 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 Zig programming language

Source code in the zig programming language

const std = @import("std");
const expect = std.testing.expect;
const stdout = std.io.getStdOut().outStream();

pub fn main() !void {
    var i: u32 = 2;
    try stdout.print("The first few perfect numbers are: ", .{});
    while (i <= 10_000) : (i += 2) if (propersum(i) == i)
        try stdout.print("{} ", .{i});
    try stdout.print("\n", .{});
}

fn propersum(n: u32) u32 {
    var sum: u32 = 1;
    var d: u32 = 2;
    while (d * d <= n) : (d += 1) if (n % d == 0) {
        sum += d;
        const q = n / d;
        if (q > d)
            sum += q;
    };
    return sum;
}

test "Proper divisors" {
    expect(propersum(28) == 28);
    expect(propersum(71) == 1);
    expect(propersum(30) == 42);
}

  

You may also check:How to resolve the algorithm Search a list of records step by step in the Raku programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the Oz programming language
You may also check:How to resolve the algorithm Keyboard input/Keypress check step by step in the Wren programming language
You may also check:How to resolve the algorithm Reduced row echelon form step by step in the Factor programming language
You may also check:How to resolve the algorithm Numerical integration step by step in the Chapel programming language