We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 8eb5ef5 commit 926dd34Copy full SHA for 926dd34
1 file changed
13. logic/beginners/sum_first_natural_num.py
@@ -0,0 +1,29 @@
1
+# Sum of First N Natural Numbers
2
+# Problem: Write a Python function that takes an integer n as input and returns the sum of the first n natural numbers.
3
+# Input: An integer n.
4
+# Output: The sum of the first n natural numbers.
5
+
6
7
+def sum_natural_numbers(n):
8
9
+ natural_sum = 0 # for adding natural numbers
10
+ change_num = 0 # for changing the natural numbers
11
12
+ for i in range(n):
13
+ change_num += 1
14
+ natural_sum += change_num
15
+ return natural_sum
16
17
+print(sum_natural_numbers(4))
18
19
20
+#! the optimized version
21
+# we can exclude the 'change_num'
22
23
+def sum_natural_numbers1(n):
24
25
+ sum = 0
26
+ for i in range(1, n+1): #! why n+1 : Commentary Below
27
+ sum += i
28
+ return sum
29
0 commit comments