n = int(input("Enter a number: "))
sum_of_numbers = n * (n + 1) // 2
print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")
Code Explanation
Input:
n = int(input("Enter a number: "))
input(): Prompts the user to enter a number.
int(): Converts the entered value (a string) into an integer.
๐
n represents the count of natural numbers to sum.
Sum Calculation
sum_of_numbers = n * (n + 1) // 2
This implements the mathematical formula for the sum of the first
๐ natural numbers
2: Divides the product by 2 using integer division (ensures the result is an integer).
Output
print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")
f"The sum of the first {n} natural numbers is: {sum_of_numbers}":
Formats the string to display
๐
n and the calculated sum.
0 Comments:
Post a Comment