Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: Square root digital expansion : Problem 80 : Project Euler : Pyhton Code

Wednesday, October 22, 2014

Square root digital expansion : Problem 80 : Project Euler : Pyhton Code


Square root digital expansion : Problem 80 : Project Euler

It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all. The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475. For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.

One of the easy way to solve the problem is to use High Precision Python library for Floating point Numbers

>>> from bigfloat import *
>>> sqrt(2, precision(100))  # compute sqrt(2) with 100 bits of precision
BigFloat.exact('1.4142135623730950488016887242092', precision=100)
 
Nonetheless you have to download the bigfloat package. This method does not give the flavor of maths!
I have rather used the decimal module which provides support for decimal floating point arithmetic and have used Newton - Raphson method to calculate the square root correct to 10**(110) places!

import math
from decimal import *
def sqRootDigitalExpansion():
    def f(x,n):
        getcontext().prec = 130
        return Decimal(x**2-n)
    def fderivative(x):
        getcontext().prec = 130
        return Decimal(2*x)
    n = 1
    totalSum = 0
    while n < 100:    
        if n == 1 or n == 4 or n == 9 or n == 16 or n == 25 or n == 36 or n == 49 or n == 64 or n == 81:
            n = n + 1
            continue
        a = 1
        b = -1
        xn = 0
        error = 0.0;
        x0=a
        while True:
           getcontext().prec = 130   
           (xn)=(x0)-((f(x0,n)/fderivative(x0)))
           (error)=(math.fabs(xn-x0))
           x0=xn
           if error < 10**(-110):
               break
        mylist = str(xn).split(".")
        sumR = 0
        for i in range(len(mylist[0])):   
            sumR = sumR + int(mylist[0][i])
        for i in range (0,100-len(mylist[0])):
            sumR = sumR + int(mylist[1][i])
        print ("Digital Sum of the root (100 digits) ",sumR," for the number ",n)
        totalSum = totalSum + sumR
        n = n + 1
    print(totalSum)
sqRootDigitalExpansion()

No comments:

Post a Comment