Xyris  0.5
primes.cpp
Go to the documentation of this file.
1 /**
2  * @file primes.cpp
3  * @author Micah Switzer ([email protected])
4  * @brief Prime computation tasks
5  * @version 0.1
6  * @date 2020-12-30
7  *
8  * @copyright Copyright the Xyris Contributors (c) 2021
9  *
10  */
11 #include <stddef.h>
12 #include <Library/Bitset.hpp>
13 #include <Scheduler/tasks.hpp>
14 #include <Applications/primes.hpp>
16 
17 namespace Apps {
18 
19 // this value can be tweaked based on memory constraints
20 #define PRIME_MAX_SQRT 4000
21 #define PRIME_MAX (PRIME_MAX_SQRT * PRIME_MAX_SQRT)
22 #define PRIMES_SIZE (PRIME_MAX / (sizeof(size_t) * CHAR_BIT))
23 static Bitset<PRIMES_SIZE> map(SIZE_MAX);
24 
25 static size_t prime_current;
26 
27 void find_primes(void)
28 {
29  for (prime_current = 2; prime_current < PRIME_MAX_SQRT; prime_current++) {
30  if (!map.Test(prime_current)) continue;
31  for (size_t j = prime_current * prime_current; j < PRIME_MAX; j += prime_current) {
32  map.Reset(j);
33  }
34  }
35 }
36 
37 void show_primes(void)
38 {
39  do {
40  tasks_nano_sleep(1000ULL * 1000 * 1000);
41  size_t pct = (prime_current * 100) / PRIME_MAX_SQRT;
42  Console::printf("\e[s\e[23;0fComputing primes: %%%zu\e[u", pct);
43  } while (prime_current < PRIME_MAX_SQRT);
44 
45  size_t count = 0;
46  for (size_t i = 2; i < PRIME_MAX; i++) {
47  count += map.Test(i);
48  }
49  Console::printf("\e[s\e[23;0fFound %zu primes between 2 and %u.\e[u", count, PRIME_MAX);
50 }
51 
52 }
PRIME_MAX_SQRT
#define PRIME_MAX_SQRT
Definition: primes.cpp:20
Apps
Definition: animation.cpp:14
Apps::show_primes
void show_primes(void)
Starts a task to display number of primes found by find_primes.
Definition: primes.cpp:37
console.hpp
Framebuffer console.
Bitset.hpp
A basic bitmap implementation.
tasks.hpp
tasks_nano_sleep
void tasks_nano_sleep(uint64_t time)
Sleep for a given period of time (in nanoseconds).
Definition: tasks.cpp:506
primes.hpp
Prime computation tasks.
Apps::find_primes
void find_primes(void)
Starts a task to find prime numbers.
Definition: primes.cpp:27
PRIME_MAX
#define PRIME_MAX
Definition: primes.cpp:21
Console::printf
int printf(const char *fmt,...)
Definition: console.cpp:273
Bitset
Definition: Bitset.hpp:21