From aafaeb91fc7adf59204fce27265fcc0feec449dd Mon Sep 17 00:00:00 2001 From: Philippe Zwietering Date: Sat, 6 Nov 2021 13:48:12 +0100 Subject: [PATCH] I solved it by using someones pseudocode and to be honest I don't completely understand how it works --- projecteuler/064/main.cpp | 76 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 projecteuler/064/main.cpp diff --git a/projecteuler/064/main.cpp b/projecteuler/064/main.cpp new file mode 100644 index 0000000..abb9e68 --- /dev/null +++ b/projecteuler/064/main.cpp @@ -0,0 +1,76 @@ +/* +Find the number of continued fractions for the square roots of n <= 10000 which have an odd period +*/ + +#include + +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 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::high_resolution_clock::now() - start); + cout << (float)duration.count()/1000 << endl; + return 0; +}