We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I solved this problem using Pell's Equation fundermental solution.
importmathdefis_perfect_square(n):"""Check if a number is a perfect square."""root=int(math.sqrt(n))returnroot*root==ndefcontinued_fraction_sqrt(n):"""Compute the continued fraction representation of sqrt(n)."""m,d,a=0,1,int(math.sqrt(n))initial_a=aperiod=[]ifinitial_a*initial_a==n:#PerfectsquarecheckreturnNone,[]whileTrue:m=d*a-md=(n-m*m)// da=(initial_a+m)// dperiod.append(a)ifa==2*initial_a:#Periodrepeatsherebreakreturninitial_a,perioddefsolve_pell_equation(n):"""Solve Pell's equation x^2 - n * y^2 = 1 for the minimal solution."""ifis_perfect_square(n):raiseValueError(f"The given number {n}isaperfectsquare,nosolutionexists.")a0,period=continued_fraction_sqrt(n)ifnotperiod:returnNone# Compute convergents using the periodic continued fractionp_prev,p_curr=1,a0q_prev,q_curr=0,1forkinrange(1,len(period)*2+1):#Repeatuntilperiodlengthishita_k=period[(k-1)%len(period)]p_next=a_k*p_curr+p_prevq_next=a_k*q_curr+q_prev# Check if the solution satisfies Pell's equationifp_next*p_next-n*q_next*q_next==1:returnp_next,q_next# Update for the next iterationp_prev,p_curr=p_curr,p_nextq_prev,q_curr=q_curr,q_nextif__name__=='__main__':N=int(input())max_x=0index=2foriinrange(2,N+1):try:x,y=solve_pell_equation(i)ifx>max_x:max_x=xindex=iexceptValueErrorase:passprint(index)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #66: Diophantine equation
You are viewing a single comment's thread. Return to all comments →
I solved this problem using Pell's Equation fundermental solution.