Sum multiples of 3 and 5: Difference between revisions

Content added Content deleted
(Added Gambas)
(Re-edited my previous submission to use compile-time metaprogramming.)
Line 5,038: Line 5,038:


=={{header|Zig}}==
=={{header|Zig}}==
Note that solving for 1e20 requires numbers > 128 bits. However, Zig supports fixed size integers up to 65,556 bits, and with Zig, it's possible to figure out at compile-time what the maximum width of an integer should be at run-time.
Inclusion/Exclusion mapping i64 -> i128 (largest integers supported in Zig natively)
<syntaxhighlight lang="zig">
<syntaxhighlight lang="zig">
const std = @import("std");
const std = @import("std");
const stdout = std.io.getStdOut().writer();


fn sumdiv(n: i64, d: i64) i128 {
fn DoubleWide(comptime n: anytype) type {
const Signedness = std.builtin.Signedness;
var m: i128 = @divFloor(n, d);
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;
return @divExact(m * (m + 1), 2) * d;
}
}


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


pub fn main() !void {
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
try stdout.print("The sum of the multiples of 3 and 5 below 1000 is {}\n", .{sum3or5(999)});

try stdout.print("The sum of the multiples of 3 and 5 below 1e18 is {}\n", .{sum3or5(999_999_999_999_999_999)});
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)});
}
}

</syntaxhighlight>
</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below 1e18 is 233333333333333333166666666666666668
The sum of the multiples of 3 and 5 below 1e20 is 2333333333333333333316666666666666666668

</pre>
</pre>
=={{header|zkl}}==
=={{header|zkl}}==