-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler.hpp
72 lines (66 loc) · 1.41 KB
/
euler.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef _euler_hpp_
#define _euler_hpp_
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <vector>
#include <sstream>
#include <iostream>
namespace euler
{
// generate a set of primes from [2,n]
template <typename T>
std::set<T> primes(T n)
{
std::set<T> p;
std::vector<bool> sieve(n+1);
for (auto i = 2; i <= n; ++i) {
if (sieve[i]) {
continue;
}
if (!sieve[i]) {
p.insert(i);
for (auto j = i; j <= n; j+=i) {
sieve[j] = true;
}
}
}
return p;
}
// generate factors for n
template <typename T>
std::map<T,std::size_t> factors(T n, const std::set<T> & p)
{
std::map<T,std::size_t> f;
auto bound = std::sqrt(n) + 1;
for (auto i = p.cbegin(); (i != p.cend()) || (*i > bound); ++i) {
const auto prime = *i;
std::size_t order = 0;
for (auto d = n; (d % prime) == 0; d /= prime) {
++order;
}
if (order) {
f[prime] = order;
}
}
return f;
}
// returns true if the number is a palindrome
template <typename T>
bool palindrome(T n)
{
std::ostringstream s;
s << n;
auto r = s.str();
return std::equal(r.begin(), r.end(),
r.rbegin());
}
// return the nth triangle number
template <typename T>
T triangle(T n)
{
return (n*(n+1))/2;
}
} // namespace euler
#endif //_euler_hpp_