Вопрос задан 16.06.2023 в 00:00. Предмет Информатика. Спрашивает Фортуна Настя.

Питон Натуральное число называется числом Армстронга, если сумма цифр числа, возведенных в K -ю

степень (где K – количество цифр в числе) равна самому числу. Например, 153 = 1 3 + 5 3 + 3 3 . Напишите программу, которая находит все числа Армстронга на отрезке [ a , b ] . Входные данные Входная строка содержит два натуральных числа – значения a и b , разделённых пробелами. Гарантируется, что a ≤ b . Выходные данные Программа должна вывести в одну строчку все числа Армстронга на отрезке [ a , b ] , разделив их пробелами. Если таких чисел нет, программа должна вывести число -1. Примеры входные данные 100 400 выходные данные 153 370 371 входные данные 500 600 выходные данные -1
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Александрова Александра.

def armstrong_number(x):

   l = len(str(x))

   s = 0

   t = x

   while x > 0:

       s += (x % 10)**l

       x //= 10

   return s == t

a, b = [int(x) for x in input().split()]

flag = False

for i in range(a, b+1):

   if armstrong_number(i):

       print(i, end = ' ')

       flag = True

if not flag:

   print(-1)

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

To find all Armstrong numbers in a given range [a, b], we can iterate through each number in the range and check if it satisfies the Armstrong number condition. Here's a Python program that solves this problem:

```python def is_armstrong_number(num): # Convert the number to a string to iterate through its digits num_str = str(num) # Get the number of digits in the number num_digits = len(num_str) # Calculate the sum of each digit raised to the power of the number of digits armstrong_sum = sum(int(digit) ** num_digits for digit in num_str) # Check if the sum is equal to the original number return armstrong_sum == num

def find_armstrong_numbers(a, b): # Initialize an empty list to store the Armstrong numbers armstrong_numbers = [] # Iterate through each number in the range [a, b] for num in range(a, b + 1): # Check if the number is an Armstrong number if is_armstrong_number(num): # If it is, add it to the list armstrong_numbers.append(num) # Check if any Armstrong numbers were found if len(armstrong_numbers) > 0: # If there are, join them into a string separated by spaces result = ' '.join(str(num) for num in armstrong_numbers) else: # If no Armstrong numbers were found, set the result to -1 result = '-1' # Return the result return result

# Test the function with the given examples print(find_armstrong_numbers(100, 400)) # Output: 153 370 371 print(find_armstrong_numbers(500, 600)) # Output: -1 ```

This program defines two functions: `is_armstrong_number()` and `find_armstrong_numbers()`. The `is_armstrong_number()` function checks if a given number is an Armstrong number by calculating the sum of each digit raised to the power of the number of digits and comparing it to the original number. The `find_armstrong_numbers()` function iterates through each number in the given range and checks if it is an Armstrong number using the `is_armstrong_number()` function. It then returns a string containing all the Armstrong numbers found, separated by spaces, or -1 if no Armstrong numbers were found.

Please note that this program assumes that the input values `a` and `b` are positive integers, and `a` is less than or equal to `b`.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос