Sum multiples of 3 and 5: Difference between revisions
Re-edited my previous submission to use compile-time metaprogramming.
(Added Gambas) |
(Re-edited my previous submission to use compile-time metaprogramming.) |
||
Line 5,038:
=={{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.
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().writer();▼
fn
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) {
return @divExact(m * (m + 1), 2) * d;
}
fn sum3or5(n:
return sumdiv(n, 3) + sumdiv(n, 5) - sumdiv(n, 15);
}
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
}
</syntaxhighlight>
{{Out}}
<pre>
The sum of the multiples of 3 and 5 below 1000 is 233168
The sum of the multiples of 3 and 5 below
</pre>
=={{header|zkl}}==
|