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

Published on 12 May 2024 09:40 PM

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

Table of Contents

Problem Statement

From Wikipedia, the free encyclopedia:

Find and print the first   8   happy numbers. Display an example of your output here on this page.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Happy numbers step by step in the Zig programming language

Source code in the zig programming language

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

pub fn main() !void {
    try stdout.print("The first 8 happy numbers are: ", .{});
    var n: u32 = 1;
    var c: u4 = 0;
    while (c < 8) {
        if (isHappy(n)) {
            c += 1;
            try stdout.print("{} ", .{n});
        }
        n += 1;
    }
    try stdout.print("\n", .{});
}

fn isHappy(n: u32) bool {
    var t = n;
    var h = sumsq(n);
    while (t != h) {
        t = sumsq(t);
        h = sumsq(sumsq(h));
    }
    return t == 1;
}

fn sumsq(n0: u32) u32 {
    var s: u32 = 0;
    var n = n0;
    while (n > 0) : (n /= 10) {
        const m = n % 10;
        s += m * m;
    }
    return s;
}

  

You may also check:How to resolve the algorithm Rock-paper-scissors step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Create a file step by step in the i programming language
You may also check:How to resolve the algorithm Text processing/2 step by step in the Wren programming language
You may also check:How to resolve the algorithm OpenGL step by step in the C programming language
You may also check:How to resolve the algorithm Filter step by step in the GAP programming language