Avatar of fdumontmd

fdumontmd's solution

to Nth Prime in the C Track

Published at Sep 16 2019 · 0 comments
Instructions
Test suite
Solution

Given a number n, determine what the nth prime is.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

If your language provides methods in the standard library to deal with prime numbers, pretend they don't exist and implement them yourself.

Getting Started

Make sure you have read the "Guides" section of the C track on the Exercism site. This covers the basic information on setting up the development environment expected by the exercises.

Passing the Tests

Get the first test compiling, linking and passing by following the three rules of test-driven development.

The included makefile can be used to create and run the tests using the test task.

make test

Create just the functions you need to satisfy any compiler errors and get the test to fail. Then write just enough code to get the test to pass. Once you've done that, move onto the next test.

As you progress through the tests, take the time to refactor your implementation for readability and expressiveness and then go on to the next test.

Try to use standard C99 facilities in preference to writing your own low-level algorithms or facilities by hand.

Source

A variation on Problem 7 at Project Euler http://projecteuler.net/problem=7

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

test_nth_prime.c

#include "vendor/unity.h"
#include "../src/nth_prime.h"

void setUp(void)
{
}

void tearDown(void)
{
}

static void test_first_prime(void)
{
   TEST_ASSERT_EQUAL_UINT32(2, nth(1));
}

static void test_second_prime(void)
{
   TEST_IGNORE();               // delete this line to run test
   TEST_ASSERT_EQUAL_UINT32(3, nth(2));
}

static void test_sixth_prime(void)
{
   TEST_IGNORE();
   TEST_ASSERT_EQUAL_UINT32(13, nth(6));
}

static void test_large_prime(void)
{
   TEST_IGNORE();
   TEST_ASSERT_EQUAL_UINT32(104743, nth(10001));
}

static void test_weird_case(void)
{
   TEST_IGNORE();
   TEST_ASSERT_EQUAL_UINT32(0, nth(0));
}

int main(void)
{
   UnityBegin("test/test_nth_prime.c");

   RUN_TEST(test_first_prime);
   RUN_TEST(test_second_prime);
   RUN_TEST(test_sixth_prime);
   RUN_TEST(test_large_prime);
   RUN_TEST(test_weird_case);

   return UnityEnd();
}

src/nth_prime.h

#ifndef NTH_PRIME_H
#define NTH_PRIME_H

#include <stdint.h>

uint32_t nth(uint32_t n);

#endif

src/nth_prime.c

#include "nth_prime.h"

#include <stdbool.h>
#include <stdlib.h>

/*
  Design: implement an Erastothene sieve with a partial min priority queue
  that contains multiples of all identified primes.
 */

struct prime_mult {
  uint32_t step;
  uint32_t mult;
};

struct prime_generator {
  uint32_t cursor;
  size_t len;
  size_t cap;
  struct prime_mult* items;
};

bool
pg_init(struct prime_generator *pg, size_t init_cap)
{
  pg->cursor = 2;
  pg->cap = init_cap;
  pg->len = 0;
  pg->items = calloc(pg->cap, sizeof(struct prime_generator));
  return pg->items;
}

void
pg_free(struct prime_generator *pg)
{
  free(pg->items);
}

bool
pg_extend(struct prime_generator *pg)
{
  struct prime_mult* items =
    realloc(pg->items, pg->cap * 2 * sizeof(struct prime_mult));
  if (items) {
    pg->cap *= 2;
    pg->items = items;
  }

  return items;
}

void
pg_swap(struct prime_generator *pg, size_t i, size_t j)
{
  struct prime_mult tmp = pg->items[i];
  pg->items[i] = pg->items[j];
  pg->items[j] = tmp;
}

bool
pg_push(struct prime_generator *pg, uint32_t prime)
{
  if (pg->len == pg->cap) {
    if (!pg_extend(pg))
      return false;
  }
  pg->items[pg->len].step = prime;
  pg->items[pg->len].mult = 2 * prime;
  pg->len += 1;

  /* computation is easier if we count from 1; remember to subtract 1
     when indexing
  */
  size_t cur = pg->len;

  while (cur > 1) {
    if (pg->items[cur / 2 - 1].mult > pg->items[cur - 1].mult) {
      pg_swap(pg, cur / 2 -1, cur - 1);
    } else {
      break;
    }
    cur /= 2;
  }

  return true;
}

void
pg_update_head(struct prime_generator *pg)
{
  if (pg->len > 0) {
    pg->items[0].mult += pg->items[0].step;

    size_t cur = 1;
    /* cur == pg->len would be valid, but also last element */
    for(; cur < pg->len;) {
      size_t left = cur * 2;
      if (left > pg->len)
        break;

      size_t right = cur * 2 + 1;

      uint32_t cur_mult = pg->items[cur - 1].mult;
      uint32_t left_mult = pg->items[left - 1].mult;
      uint32_t right_mult =
        right <= pg->len ? pg->items[right - 1].mult : UINT32_MAX;

      if (cur_mult <= left_mult && cur_mult <= right_mult)
        break;

      if (left_mult < right_mult) {
        pg_swap(pg, cur - 1, left - 1);
        cur = left;
      } else {
        pg_swap(pg, cur - 1, right - 1);
        cur = right;
      }
    }
  }
}

uint32_t
pg_next_prime(struct prime_generator *pg)
{
  uint32_t candidate;
  for (;;) {
    candidate = pg->cursor;
    pg->cursor += 1;
    if (pg->len == 0 || candidate < pg->items[0].mult) {
      pg_push(pg, candidate);
      break;
    }

    while (pg->items[0].mult == candidate)
      pg_update_head(pg);
  }

  return candidate;
}

uint32_t
nth(uint32_t n)
{
  /* makes absolutely no sense, but the tests insist on it */
  uint32_t current_prime = 0;

  struct prime_generator pg;
  pg_init(&pg, n);

  for (uint32_t i = 0; i < n; i++) {
    current_prime = pg_next_prime(&pg);
  }

  pg_free(&pg);

  return current_prime;
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?