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"); |
||
⚫ | |||
fn |
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) { |
|||
⚫ | |||
return @divExact(m * (m + 1), 2) * d; |
return @divExact(m * (m + 1), 2) * d; |
||
} |
} |
||
fn sum3or5(n: |
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 { |
||
⚫ | |||
⚫ | |||
⚫ | |||
var s: usize = 0; |
|||
for (1..1000) |n| { |
|||
if (n % 3 == 0 or n % 5 == 0) |
|||
s += n; |
|||
} |
|||
⚫ | |||
⚫ | |||
} |
} |
||
</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 |
The sum of the multiples of 3 and 5 below 1e20 is 2333333333333333333316666666666666666668 |
||
</pre> |
</pre> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |