Skip to content

Commit

Permalink
added some number theory algos
Browse files Browse the repository at this point in the history
  • Loading branch information
spirosmaggioros committed Jan 28, 2024
1 parent 83c937c commit 1df011f
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 3 deletions.
11 changes: 11 additions & 0 deletions examples/algorithms/mersenne_primes.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#ifdef __cplusplus
#include "../../src/algorithms/number_theory/mersenne_primes.h"
#endif

int main() {
int64_t n = 100;
std::vector<int> first_10_mersenne_primes = mersenne(10000000);
for (auto &x : first_10_mersenne_primes) {
std::cout << x << " ";
}
}
23 changes: 23 additions & 0 deletions src/algorithms/number_theory/eratosthenes_sieve.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
#ifndef ERATOSTHENES_SIEVE_H
#define ERATOSTHENES_SIEVE_H

#ifdef __cplusplus
#include <assert.h>
#include <iostream>
#include <vector>
#endif

std::vector<bool> soe(int64_t n) {
assert(n != 0);
std::vector<bool> prime(n + 1, true);
for (int64_t p = 2; p * p <= n; ++p) {
if (prime[p]) {
for (int64_t i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
return prime;
}

#endif
6 changes: 3 additions & 3 deletions src/algorithms/number_theory/gcd.h
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#ifndef GCD_H
#define GCD_H

#ifdef __cplusplus
#include <iostream>
#endif

#ifndef GCD_H
#define GCD_H

/*
*binary_gcd function.
*@param a: first element.
Expand Down
27 changes: 27 additions & 0 deletions src/algorithms/number_theory/mersenne_primes.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#ifndef MERSENNE_PRIMES_H
#define MERSENNE_PRIMES_H

#ifdef __cplusplus
#include "eratosthenes_sieve.h"
#include <iostream>
#endif

/*
*mersenne function.
*@param n: the upper bound
*Returns vector<int>: the vector includes the elements "p" from m = 2^p - 1 for
*which p gives us a mersenne prime number.
*/
std::vector<int> mersenne(int64_t n) {
std::vector<bool> prime = soe(n);
std::vector<int> elements;
int64_t k = 2;
while ((1 << k) - 1 <= n) {
if (prime[(1 << k) - 1]) {
elements.push_back(k);
}
k++;
}
return elements;
}
#endif

0 comments on commit 1df011f

Please sign in to comment.