File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n * sqrt(n))
2
+ // Space: O(sqrt(n))
3
+
4
+ class Solution {
5
+ public:
6
+ int sumFourDivisors (vector<int >& nums) {
7
+ int result = 0 ;
8
+ for (const auto & num : nums) {
9
+ const auto & facs = factorize (num);
10
+ if (facs.size () == 1 && facs[0 ].second == 3 ) {
11
+ const auto & p = facs[0 ].first ;
12
+ result += int (pow (p, 4 ) - 1 ) / (p - 1 ); // p^0 + p^1 +p^2 +p^3
13
+ } else if (facs.size () == 2 &&
14
+ facs[0 ].second == 1 &&
15
+ facs[1 ].second == 1 ) {
16
+ const auto & [p, q] = pair (facs[0 ].first , facs[1 ].first );
17
+ result += (1 + p) * (1 + q);
18
+ }
19
+ }
20
+ return result;
21
+ }
22
+
23
+ private:
24
+ vector<pair<int , int >> factorize (int x) {
25
+ vector<pair<int , int >> result;
26
+ for (int d = 2 ; d * d <= x; d += (d == 2 ) ? 1 : 2 ) {
27
+ int e = 0 ;
28
+ for (; x % d == 0 ; ++e) {
29
+ x /= d;
30
+ }
31
+ if (e) {
32
+ result.emplace_back (d, e);
33
+ }
34
+ }
35
+ if (x > 1 ) {
36
+ result.emplace_back (x, 1 );
37
+ }
38
+ return result;
39
+ }
40
+ };
41
+
42
+ // Time: O(n * sqrt(n))
43
+ // Space: O(sqrt(n))
44
+ class Solution2 {
45
+ public:
46
+ int sumFourDivisors (vector<int >& nums) {
47
+ int result = 0 ;
48
+ for (const auto & num : nums) {
49
+ vector<int > facs;
50
+ for (int i = 1 ; i * i <= num; ++i) {
51
+ if (num % i) {
52
+ continue ;
53
+ }
54
+ facs.emplace_back (i);
55
+ if (i != num / i) {
56
+ facs.emplace_back (num / i);
57
+ }
58
+ }
59
+ if (facs.size () == 4 ) {
60
+ result += accumulate (cbegin (facs), cend (facs), 0 );
61
+ }
62
+ }
63
+ return result;
64
+ }
65
+ };
You can’t perform that action at this time.
0 commit comments