Project Euler #64: Odd period square roots

  • + 0 comments

    Here 100/- Points Solution in C#

    using System;
    using System.Collections.Generic;
    
    namespace PerfectSquareFractions
    {
        class Program
        {
            static int PerfArc(int n)
            {
                int root = (int)Math.Sqrt(n);
                if (root * root == n)
                {
                    return 0;
                }
                int a = 1;
                List<int> listaint = new List<int> { root };
                int den = n - root * root;
                List<double> lista_inv_frac = new List<double> { (Math.Sqrt(n) + root) / den };
                int per = 0;
                while (true)
                {
                    int part_int = (int)lista_inv_frac[lista_inv_frac.Count - 1];
                    root = (den * part_int) / a - root;
                    a = den / a;
                    den = n - root * root;
                    double invfrac = a * (Math.Sqrt(n) + root) / den;
                    listaint.Add(part_int);
                    lista_inv_frac.Add(invfrac);
                    per++;
                    if (invfrac == lista_inv_frac[0])
                    {
                        return per;
                    }
                }
            }
    
            static void Main(string[] args)
            {
                int n = int.Parse(Console.ReadLine());
                int cntodd = 0;
                for (int k = 2; k <= n; k++)
                {
                    if (PerfArc(k) % 2 == 1)
                    {
                        cntodd++;
                    }
                }
    
                Console.WriteLine(cntodd);
            }
        }
    }