Project Euler Homework

039.cpp

00001 #include <iostream>
00002 #include <set>
00003 using namespace std;
00004 
00005 const unsigned MAX = 1000;
00006 
00007 unsigned gcd(unsigned m,unsigned n)
00008 {
00009         //assume m>n
00010         unsigned r=m%n;
00011         while (r>0) {
00012                 m=n;
00013                 n=r;
00014                 r = m%n;
00015         }
00016         return n;
00017 }
00018 
00019 int main()
00020 {
00021         multiset<unsigned> set_p;
00022         set<set<unsigned> > lookup_table;
00023 
00024         for (unsigned m=1;m<=21;m++)
00025                 for (unsigned n=m-1;n>0;n--) {
00026                         //the triples are primitive if m,n are coprime and exactly one of them is even
00027                         if ((m&1) == (n&1))continue;
00028                         if (gcd(m,n)!=1) continue;
00029 
00030                         //pythagorean triples by euler's formula
00031                         unsigned a=m*m-n*n;
00032                         unsigned b=2*m*n;
00033                         unsigned c=m*m+n*n;
00034                         unsigned p = a+b+c;
00035 
00036                         for (unsigned pk=p;pk<=MAX;pk+=p) {
00037                                 if (pk==120)cout << a << ' '<<b <<' '<< c<<endl;
00038                                 set_p.insert(pk);
00039                         }
00040 
00041                 }
00042         //now count and find p with max no of triples
00043         unsigned MAX_p=0;
00044         unsigned best_p=1;
00045         for (unsigned p=1;p<=MAX;p++) {
00046                 unsigned cnt=set_p.count(p);
00047 
00048                 if (cnt>MAX_p) {
00049                         MAX_p = cnt;
00050                         best_p = p;
00051                         //cout << p << '\t' << cnt << endl;
00052                 }
00053         }
00054         cout << best_p << endl;
00055         return 0;
00056 }
 All Classes Files Functions Variables