[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.
Whereas working as a researcher in distributed programs, Dr. Christian Mayer discovered his love for instructing pc science college students.
To assist college students attain larger ranges of Python success, he based the programming schooling web site Finxter.com that has taught exponential expertise to thousands and thousands of coders worldwide. He’s the writer of the best-selling programming books Python One-Liners (NoStarch 2020), The Artwork of Clear Code (NoStarch 2022), and The E book of Sprint (NoStarch 2022). Chris additionally coauthored the Espresso Break Python sequence of self-published books. He’s a pc science fanatic, freelancer, and proprietor of one of many high 10 largest Python blogs worldwide.
His passions are writing, studying, and coding. However his best ardour is to serve aspiring coders by way of Finxter and assist them to spice up their expertise. You may be a part of his free e-mail academy right here.
[ad_2]