-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheuler29.cs
125 lines (106 loc) · 2.78 KB
/
euler29.cs
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static int A = 8;
static int B = A;
static void Main(string[] args)
{
int sCount = DistinctTerms();
Console.WriteLine("Smart {0}", sCount);
int bCount = BruteForce();
Console.WriteLine("BruteForce {0}", bCount);
}
static HashSet<int> Divisors(int b)
{
HashSet<int> divisors = new HashSet<int>() {};
if (b == 2) return divisors;
for (int d = 2; d <= (int)Math.Ceiling(Math.Sqrt(b)); d++)
{
if (b % d == 0)
{
divisors.Add(d);
divisors.Add(b / d);
}
}
return divisors;
}
static int DistinctTerms()
{
int terms = 0;
for (int a = 2; a <= A; a++)
{
for (int b = 2; b <= B; b++)
{
Console.WriteLine("a={0} b={1} a^b={2}", a, b, Math.Pow(a,b));
int unique = CountUnique(a, b);
terms += unique;
//Console.WriteLine("total={0}\n", terms);
}
}
return terms;
}
static bool RangeCheck(int a, int d)
{
double minLimitD = Math.Log(A, 2);
double minLimitA = Math.Sqrt(A);
if (a > minLimitA || d > minLimitD)
{
return false;
}
int pow = (int)Math.Pow(a, d);
if (2 <= pow && pow <= A)
{
return true;
}
return false;
}
static int CountUnique(int a, int b, int original = 0)
{
int count = 1;
HashSet<int> divisors = Divisors(a);
// special case
if (divisors.Count == 1)
{
Console.WriteLine("\t-->Power");
int d = divisors.First();
int n = a / d;
return CountUnique(d, n * b, original: a);
}
foreach (int d in Divisors(b))
{
if ( original == 0 && RangeCheck(a, d))
{
count -= 1;
Console.WriteLine("\ta={0} d={1} (a^d)^(b/d)={4}\ta^d={3} b/d={5} RangeCheck({3})={2}", a, d, RangeCheck(a,d), Math.Pow(a,d), Math.Pow(Math.Pow(a,d),b/d), b/d);
Console.WriteLine("\t\tcount-- original=0)");
}
if ( original != 0 && Math.Pow(a,d) > original && RangeCheck(a, d))
{
Console.WriteLine("\ta={0} d={1} (a^d)^(b/d)={4}\ta^d={3} b/d={5} RangeCheck({3})={2}", a, d, RangeCheck(a,d), Math.Pow(a,d), Math.Pow(Math.Pow(a,d),b/d), b/d);
Console.WriteLine("\t\tcount-- original!=0 && a>= original)");
count -= 1;
}
}
Console.WriteLine("\t-->CountUnique()={0}", count);
return count;
}
static int BruteForce()
{
HashSet<long> powers = new HashSet<long>();
for (int a = 2; a <= A; a++)
{
for (int b = 2; b <= B; b++)
{
long pow = (long)Math.Pow(a, b);
if (powers.Contains(pow))
{
Console.WriteLine("found bouble {0} {1} {2}", a, b, pow);
}
powers.Add(pow);
}
}
return powers.Count;
}
}