Write a program that counts how many of the squares of the numbers from 1 to 100 end in a
4 and how many end in a 9.
count_4 = 0
count_9 = 0
# loop through the numbers from 1 to 100
for i in range(1, 101):
# square the number
squared = i ** 2
# convert the squared number to a string
squared_str = str(squared)
# check if the last character is a 4
if squared_str[-1] == '4':
# if it is, increment the count
count_4 += 1
# check if the last character is a 9
elif squared_str[-1] == '9':
# if it is, increment the count
count_9 += 1
# print the counts
print(f"Number of squares ending in 4: {count_4}")
print(f"Number of squares ending in 9: {count_9}")
This program first sets two count variables, count_4
and count_9
, to 0. It then loops through the numbers from 1 to 100, squares each number, converts the squared number to a string, and checks if the last character is a 4 or a 9. If it is, it increments the appropriate count. Finally, it prints the counts.
If you run the program, it will print the counts of how many of the squares of the numbers from 1 to 100 end in a 4 and how many end in a 9. For example, if you run the program, you might see something like:
Number of squares ending in 4: 6
Number of squares ending in 9: 5
0 Comments