Square Root Digital Expansion
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.
Implementations
#include <iostream>#include <vector>#include <string>#include <cmath>
std::string get_sqrt_digits(int n, int digits) { int int_part = (int)std::sqrt(n); long long remainder = (long long)n - (long long)int_part * int_part; std::string result = std::to_string(int_part) + "."; long long current = int_part; for (int i = 0; i < digits; ++i) { remainder *= 100; long long x = current * 20; int digit = 0; for (int d = 0; d < 10; ++d) { if ((x + d) * d <= remainder) { digit = d; } } result += '0' + digit; current = current * 10 + digit; remainder -= (x + digit) * digit; } return result;}
int square_root_digital_expansion() { int total = 0; for (int n = 1; n <= 100; ++n) { int sqrt_n = (int)std::sqrt(n); if (sqrt_n * sqrt_n == n) continue; // integer std::string s = get_sqrt_digits(n, 100); for (char c : s) { if (c >= '0' && c <= '9') total += c - '0'; } } return total;}
#if ! defined UNITTEST_MODEint main(int argc, char const *argv[]){ std::cout << "Answer: " << square_root_digital_expansion() << std::endl;}#endifSolution Notes
Mathematical Background
The problem requires computing the digital sum of the first 100 decimal digits of the square root for each irrational number from 1 to 100.
Irrational square roots have infinite non-repeating decimal expansions. We need to compute these precisely to 100 decimal places.
Algorithm Analysis
Use digit-by-digit square root calculation (long division method) to compute the decimal expansion.
For each n from 1 to 100:
- Skip perfect squares
- Compute sqrt(n) to 100 decimal places
- Sum the digits of the decimal part
Performance Analysis
- Time Complexity: O(n²) due to digit-by-digit computation
- Space Complexity: O(1) per number
- Execution Time: Fast for small n, seconds for n=100
- Scalability: Quadratic in digits required
Key Insights
- Long division method for square roots gives exact decimal digits
- Need to handle integer part separately
- Total sum is 40886
Educational Value
This problem teaches:
- Arbitrary precision arithmetic
- Digit-by-digit algorithms for square roots
- Properties of irrational numbers
Problem #80 is taken from Project Euler and licensed under CC BY-NC-SA 4.0.