How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Zig programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Zig programming language

Table of Contents

Problem Statement

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Zig programming language

Source code in the zig programming language

const std = @import("std");

fn DoubleWide(comptime n: anytype) type {
    const Signedness = std.builtin.Signedness;
    switch (@typeInfo(@TypeOf(n))) {
        .Int => |t|
            return std.meta.Int(t.signedness, t.bits * 2),
        .ComptimeInt => {
            const sz = @as(u16, @intFromFloat(@log2(@as(f64, @floatFromInt(n))))) + 1;
            return std.meta.Int(Signedness.signed, sz * 2);
        },
        else =>
            @compileError("must have integral type for DoubleWide")
    }
}

fn sumdiv(n: anytype, d: anytype) DoubleWide(n) {
    var m: DoubleWide(n) = @divFloor(n, d);
    return @divExact(m * (m + 1), 2) * d;
}

fn sum3or5(n: anytype) DoubleWide(n) {
    return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    var s: usize = 0;
    for (1..1000) |n| {
        if (n % 3 == 0 or n % 5 == 0)
            s += n;
    }
    try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{s});
    try stdout.print("The sum of the multiples of 3 and 5 below 1e20 is {}\n", .{sum3or5(99_999_999_999_999_999_999)});
}

  

You may also check:How to resolve the algorithm Formatted numeric output step by step in the Nim programming language
You may also check:How to resolve the algorithm Concurrent computing step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Substring/Top and tail step by step in the Logtalk programming language
You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the jq programming language
You may also check:How to resolve the algorithm Permutations/Derangements step by step in the Racket programming language