There are several methods to calculate the sum of the square roots of the first `n`

numbers.

## Basic Iteration

The most straightforward solution is to simply iterate from 1 to `n`

, calculate the square root of each number, and add it to a running total.

import math def sum_sqrt(n): total = 0 for i in range(1, n+1): total += math.sqrt(i) return total print(sum_sqrt(100))

**Runtime**: O(n)

## Approximate Closed Form Solution

An ** approximate** closed-form solution for the sum of square roots from 1 to

`n`

is:This reduces runtime compared to iteration. However, it is very imprecise for small `n`

and becomes more and more precise for larger `n`

.

def sum_sqrt(n): return 2/3 * ((n-2)*(n+1)**0.5-2*2**0.5)+1

**Runtime**: O(1)

## List Comprehension

A list comprehension can calculate all square roots in one line, then sum the results.

def sum_sqrt(n): return sum([math.sqrt(i) for i in range(1,n+1)]) print(sum_sqrt(10000)) # 666716.4591971082

**Runtime**: O(n)

## Map/Reduce

Use `map`

to calculate square roots, then reduce to sum results.

from functools import reduce def sum_sqrt(n): total = reduce(lambda a,b: a + b, map(math.sqrt, range(1,n+1))) return total print(sum_sqrt(n)) # 666716.4591971082

**Runtime**: O(n)

## Quick Discussion

All methods provide the same result, but the closed-form solution is most efficient and also the most imprecise with constant runtime O(1), while the others scale linearly O(n) with the number of inputs. Choose based on runtime requirements and code clarity.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.