snippets 0.1.0
Loading...
Searching...
No Matches
number_utils.hpp
Go to the documentation of this file.
1#ifndef NUMBER_UTILS_H
2#define NUMBER_UTILS_H
3
4#include <concepts>
5#include <cmath>
6#include <vector>
7#include <array>
8#include <cstdint>
9
10namespace hsc_snippets {
18 template<std::integral T>
19 int numDigits(T num) {
20 int cnt = 0;
21 while (num != 0) {
22 cnt += 1;
23 num /= 10;
24 }
25 return cnt;
26 }
27
37 template<std::integral T>
38 int numBits(T num) {
39 if (num < 0) {
40 return sizeof(T) << 3;
41 }
42 int cnt = 0;
43 while (num != 0) {
44 cnt += 1;
45 num = num >> 1;
46 }
47 return cnt;
48 }
49
56 static std::vector<int> SieveOfEratosthenes(int n) {
57 // Initialize a boolean vector "prime" with entries up to n. All entries are initially set to true.
58 // A value in prime[i] will be false if i is not a prime number, and true if it is a prime number.
59 std::vector<bool> prime(n + 1, true);
60 prime[0] = prime[1] = false; // 0 and 1 are not considered prime numbers.
61
62 // This vector will store all the prime numbers found.
63 std::vector<int> primes;
64
65 // Start iterating from the first prime number, 2, up to the square root of n.
66 // We only need to go up to sqrt(n) because if n has a divisor greater than sqrt(n),
67 // it must also have a smaller one, so all composites will have been marked by this point.
68 for (int p = 2; p <= std::sqrt(n); ++p) {
69 // If prime[p] is true, then it is a prime number.
70 if (prime[p]) {
71 // Mark all multiples of p starting from p^2 as not prime.
72 // Starting from p^2 because all smaller multiples of p would have already been marked by smaller primes.
73 for (int i = p * p; i <= n; i += p) {
74 prime[i] = false;
75 }
76 }
77 }
78
79 // Collect all prime numbers: iterate over the range up to n and
80 // add the number to the primes list if its corresponding value in the prime vector is true.
81 for (int p = 2; p <= n; ++p) {
82 if (prime[p]) {
83 primes.push_back(p);
84 }
85 }
86
87 // Return the vector containing all the primes found.
88 return primes;
89 }
90
97 static bool isPerfectSquare(std::int32_t num) {
98 if (num < 0) {
99 return false;
100 }
101 constexpr std::array<std::int32_t, 46341> arr = []()constexpr {
102 std::array<std::int32_t, 46341> _arr = {};
103 for (int i = 0; i < 46341; ++i) {
104 _arr[i] = i * i;
105 }
106 return _arr;
107 }();
108
109 return std::binary_search(arr.begin(), arr.end(), num);
110 }
111}
112
113#endif // NUMBER_UTILS_H
Definition big_integer.hpp:14
int numDigits(T num)
Definition number_utils.hpp:19
static std::vector< int > SieveOfEratosthenes(int n)
Definition number_utils.hpp:56
static bool isPerfectSquare(std::int32_t num)
Definition number_utils.hpp:97
int numBits(T num)
Definition number_utils.hpp:38