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.
Inclusion/Exclusion mapping i64 -> i128 (largest integers supported in Zig natively)
<syntaxhighlight lang="zig">
const std = @import("std");
const stdout = std.io.getStdOut().writer();
 
fn sumdivDoubleWide(comptime n: i64, d: i64anytype) i128type {
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: i128DoubleWide(n) = @divFloor(n, d);
return @divExact(m * (m + 1), 2) * d;
}
 
fn sum3or5(n: i64anytype) i128DoubleWide(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 1000 is {}\n", .{sum3or5(999)s});
try stdout.print("The sum of the multiples of 3 and 5 below 1e181e20 is {}\n", .{sum3or5(999_999_999_999_999_99999_999_999_999_999_999_999)});
}
 
</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 1e181e20 is 2333333333333333331666666666666666682333333333333333333316666666666666666668
 
</pre>
=={{header|zkl}}==
357

edits