Project Euler Problem 80 Solution

Project Euler Problem 80 Solution

Square Root Digital Expansion

by {BetaProjects} | Project Euler & HackerRank
Difficulty: Easy

Project Euler Problem 80 Statement

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\cdots$, 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.

Solution

1. Reading inputs
N,P = int(input()), int(input())

2. Setting high-precision arithmetic
from decimal import getcontext, Decimal
getcontext().prec = P + 4

3. Looping over each number, calculating the square root
total_sum = 0
for number in range(2, N+1):
    square_root = Decimal(number).sqrt()

4. Checking for perfect squares
    if square_root % 1 != 0:
        # ... sum digits ...

5. Extracting and summing the first P digits
        t = str(square_root).replace('.','')[:P]
        total_sum += sum(int(digit) for digit in t)

6. Printing the result
print(total_sum)

HackerRank version

HackerRank Project Euler 81: For the first $N$ natural numbers, find the total of the digital sums of the first $P$ $(1\le P\le 10000)$ digits for all the irrational square roots x such that $x\le N$ $(1\le N\le 1000)$.

Python Source Code

from decimal import getcontext, Decimal
N,P = int(input()), int(input())

getcontext().prec = P + 4

total_sum = 0
for number in range(2, N+1):
    square_root = Decimal(number).sqrt()
    if square_root % 1 != 0:
        t = str(square_root).replace('.','')[:P]
        total_sum+= sum(int(digit) for digit in t)

print(total_sum)