Created
June 7, 2026 18:14
-
-
Save oshea00/1179886ae584eeb18dbb8650f32d5660 to your computer and use it in GitHub Desktop.
Zig Prime Sieve
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const std = @import("std"); | |
| pub fn main(init: std.process.Init) !void { | |
| const args = try init.minimal.args.toSlice(init.arena.allocator()); | |
| const limit: usize = if (args.len >= 2) | |
| try std.fmt.parseInt(usize, args[1], 10) | |
| else | |
| 10_000_000; | |
| const is_prime = try init.gpa.alloc(bool, limit + 1); | |
| defer init.gpa.free(is_prime); | |
| @memset(is_prime, true); | |
| is_prime[0] = false; | |
| if (limit >= 1) | |
| is_prime[1] = false; | |
| var p: usize = 2; | |
| while (p <= limit / p) : (p += 1) { | |
| if (is_prime[p]) { | |
| var i: usize = p * p; | |
| while (i <= limit) : (i += p) { | |
| is_prime[i] = false; | |
| } | |
| } | |
| } | |
| var count: usize = 0; | |
| for (is_prime) |prime| { | |
| if (prime) count += 1; | |
| } | |
| std.debug.print("Number of primes up to {d} is: {d}\n", .{ limit, count }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment