2

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?

1 Answer 1

3
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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.