Write a program that asks the user to enter a value n, and then computes (1+
1/2 +
1/3 +···+
1/n
)−
ln(n). The ln function is log in the math module.
import math
# get the value of n from the user
n = int(input("Enter a value for n: "))
# initialize the sum to 0
sum = 0
# loop through the numbers from 1 to n
for i in range(1, n+1):
# add 1/i to the sum
sum += 1/i
# compute the result
result = sum - math.log(n)
# print the result
print(result)
This program first imports the math
module and gets the value of n
from the user. It then initializes a sum variable to 0 and loops through the numbers from 1 to n
, adding 1/i to the sum. It then computes the result using the formula given and prints the result.
If you run the program, it will ask you to enter a value for n
, and then it will compute and print the result. For example, if you enter 10
when prompted, you might see something like:
Enter a value for n: 10
1.5574077246549023
n
.
0 Comments