Sum of Sq. Roots of First N Numbers in Python – Be on the Proper Facet of Change

[ad_1]

There are a number of strategies to calculate the sum of the sq. roots of the primary n numbers.

Fundamental Iteration

Probably the most easy answer is to easily iterate from 1 to n, calculate the sq. root of every quantity, and add it to a working complete.

import math


def sum_sqrt(n):
    complete = 0

    for i in vary(1, n+1):
        complete += math.sqrt(i)

    return complete

print(sum_sqrt(100))

Runtime: O(n)

Approximate Closed Type Resolution

An approximate closed-form answer for the sum of sq. roots from 1 to n is:

This reduces runtime in comparison with iteration. Nonetheless, it is vitally imprecise for small n and turns into increasingly exact for bigger n.

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

Runtime: O(1)

Checklist Comprehension

A record comprehension can calculate all sq. roots in a single line, then sum the outcomes.

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/Cut back

Use map to calculate sq. roots, then cut back to sum outcomes.

from functools import cut back

def sum_sqrt(n):
    complete = cut back(lambda a,b: a + b, map(math.sqrt, vary(1,n+1)))
    return complete

print(sum_sqrt(n))
# 666716.4591971082

Runtime: O(n)

Fast Dialogue

All strategies present the identical outcome, however the closed-form answer is most effective and likewise essentially the most imprecise with fixed runtime O(1), whereas the others scale linearly O(n) with the variety of inputs. Select based mostly on runtime necessities and code readability.


[ad_2]

Leave a Comment

Your email address will not be published. Required fields are marked *