-
Notifications
You must be signed in to change notification settings - Fork 1
/
P10042.cpp
92 lines (82 loc) · 1.76 KB
/
P10042.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#define PRIME_LEN 40000
int sumDigits(int n) {
int ret = 0;
while(n > 0) {
ret += n%10;
n/=10;
}
return ret;
}
class PrimeHandler {
bool primes[PRIME_LEN];
public:
PrimeHandler() {
for(int i = 0; i < PRIME_LEN; ++i)
primes[i] = true;
// Sieve primes:
for(int i = 0; i*i < PRIME_LEN; ++i) {
if(!primes[i])
continue;
// Mark all uneven multiples as non-prime:
int basePrime = 1+2*(i+1);
for(int multiple = 3; true; multiple += 2) {
int notAPrime = basePrime*multiple;
int notAPrimeI = notAPrime/2-1;
if(notAPrimeI >= PRIME_LEN)
break;
primes[notAPrimeI] = false;
}
}
}
int nextPrime(int n) const {
int ni = n/2;
while(!primes[ni]) {
++ni;
}
//std::cerr << "Returning next prime(" << n << "): " << (1+(ni+1)*2) << std::endl;
return 1+(ni+1)*2;
}
bool isSmith(int n) {
if(n < 4)
return n == 1;
int sumDigitsN = sumDigits(n);
bool anyFactors = false;
int sumDigitsFactors = 0;
// 2:
while(n % 2 == 0) {
sumDigitsFactors += 2;
n /= 2;
anyFactors = true;
}
// 3+:
int prime = 3;
while(sumDigitsFactors <= sumDigitsN && prime*prime <= n) {
while(n % prime == 0) {
sumDigitsFactors += sumDigits(prime);
n /= prime;
anyFactors = true;
}
prime = nextPrime(prime);
}
if(n > 1)
sumDigitsFactors += sumDigits(n); // last factor.
return anyFactors && sumDigitsN == sumDigitsFactors;
}
};
int main() {
PrimeHandler ph;
int cases;
std::cin >> cases;
long n;
for(int cas = 0; cas < cases; ++cas) {
std::cin >> n;
for(int i = n+1; true; ++i) {
if(ph.isSmith(i)) {
std::cout << i << std::endl;
break;
}
}
}
return 0;
}