I'm trying to learn Zig using the website https://exercism.org/. I was solving this exercise, which requires us to find the nth prime number.
My idea was to generate all of them during comptime
and return as required; this is my current my code:
const std = @import("std");
const mem = std.mem;
fn sieve(buffer: []usize, comptime limit: usize) []usize {
if (limit < 2)
return buffer[0..0];
const sqrt_limit = std.math.sqrt(limit);
var bitset = std.StaticBitSet(limit + 1).initFull();
var n: usize = 3;
var i: usize = 1;
buffer[0] = 2;
while(n <= sqrt_limit): (n += 2) {
if (!bitset.isSet(n))
continue;
buffer[i] = n;
i += 1;
var j = 2 * n;
while (j <= limit): (j += i) {
bitset.unset(j);
}
}
while (n <= limit) : (n += 2) {
if (!bitset.isSet(i))
continue;
buffer[i] = n;
i += 1;
}
return buffer[0..i];
}
const buffer_size = std.math.maxInt(usize);
const primes_buffer = [buffer_size]usize;
const primes = sieve(primes_buffer, buffer_size - 1);
pub fn prime(allocator: mem.Allocator, number: usize) !usize {
_ = allocator;
return primes[number-1];
}
But when I try to compile this, I'm getting the following error:
nth_prime.zig:37:22: error: expected type '[]usize', found 'type'
nth_prime.zig:4:18: note: parameter type declared here
I don't understand why primes_buffer
is of type type
here; shouldn't it be a []usize
?
const primes_buffer = [buffer_size]usize;
[buffer_size]usize
is a type
. You're assigning it to a variable. It's only logical that primes_buffer
would remain a type.
You probably wanted to do
const primes_buffer: [buffer_size]usize = undefined;