Primes whose sum of digits is 25: Difference between revisions

Content added Content deleted
(→‎Stretch: Speed improvement.)
(Add Zig solution)
Line 2,303: Line 2,303:
17 primes whose sum of digits is 25.
17 primes whose sum of digits is 25.
</pre>
</pre>

=={{header|Zig}}==
{{trans|Nim}}
<syntaxhighlight lang="zig">const std = @import("std");</syntaxhighlight>
<syntaxhighlight lang="zig">fn isPrime(n: u64) bool {
if (n < 2) return false;
if (n % 2 == 0) return n == 2;
if (n % 3 == 0) return n == 3;
var d: u64 = 5;
while (d * d <= n) {
if (n % d == 0) return false;
d += 2;
if (n % d == 0) return false;
d += 4;
}
return true;
}</syntaxhighlight>
<syntaxhighlight lang="zig">fn digitSum(n_: u64) u16 {
var n = n_; // parameters are immutable, copy to var
var sum: u16 = 0;
while (n != 0) {
sum += @truncate(u16, n % 10);
n /= 10;
}
return sum;
}</syntaxhighlight>
<syntaxhighlight lang="zig">pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();

var result = std.ArrayList(u64).init(arena.allocator());
defer result.deinit();

{
var n: u64 = 3;
while (n <= 5000) : (n += 2)
if (digitSum(n) == 25 and isPrime(n))
try result.append(n);
}

const stdout = std.io.getStdOut().writer();
for (result.items, 0..) |n, i|
_ = try stdout.print("{d:4}{s}", .{ n, if ((i + 1) % 6 == 0) "\n" else " " });
}</syntaxhighlight>
{{out}}
<pre> 997 1699 1789 1879 1987 2689
2797 2887 3499 3697 3769 3877
3967 4597 4759 4957 4993</pre>