Files
contests/projecteuler/064/main.cpp

77 lines
1.6 KiB
C++

/*
Find the number of continued fractions for the square roots of n <= 10000 which have an odd period
*/
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b){
if(b == 0){
return a;
}
return gcd(b, a % b);
}
int gcd(int a, int b, int c){
return gcd(a, gcd(b, c));
}
// Pseudocode found in the video on continued fraction of square roots of integers https://www.youtube.com/watch?v=GFJsU9QsytM
bool check(int n){
float x = sqrt((float)n);
if(x != sqrt(n)){
vector<int> cf;
int a, b = 1, c = 1, d = 0;
int bn, cn, dn, g;
int b1, c1, d1;
for(int i = 0; ; ++i){
a = floor((floor(b * x) + d) / c);
cf.push_back(a);
bn = b*c;
cn = b*b*n - d*d - a*a*c*c + 2*a*c*d;
dn = a*c*c - c*d;
g = gcd(bn, cn, dn);
b = bn / g;
c = cn / g;
d = dn / g;
if(i == 0){
b1 = b;
c1 = c;
d1 = d;
} else if(b1 == b && c1 == c && d1 == d){
break;
}
}
return cf.size() % 2 == 0;
}
return false;
}
int main(){
cout << "Hello this is Patrick" << endl;
auto start = chrono::high_resolution_clock::now();
int result = 0;
for(int n = 1; n <= 10000; ++n){
result += check(n);
}
cout << result << endl;
auto duration = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start);
cout << (float)duration.count()/1000 << endl;
return 0;
}