In questo esempio, imparerai a controllare se un intero di n cifre è un numero Armstrong o meno.
Per comprendere questo esempio, dovresti avere la conoscenza dei seguenti argomenti di programmazione Python:
- Istruzione Python if … else
- Python while Loop
Un numero intero positivo è chiamato numero Armstrong di ordine n se
abcd … = a n + b n + c n + d n + …
In caso di un numero Armstrong di 3 cifre, la somma dei cubi di ciascuna cifra è uguale al numero stesso. Per esempio:
153 = 1 * 1 * 1 + 5 * 5 * 5 + 3 * 3 * 3 // 153 è un numero Armstrong.
Codice sorgente: controllare il numero Armstrong (per 3 cifre)
# Python program to check if the number is an Armstrong number or not # take input from the user num = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp> 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number")
Uscita 1
Immettere un numero: 663 663 non è un numero Armstrong
Uscita 2
Immettere un numero: 407 407 è un numero Armstrong
Qui, chiediamo un numero all'utente e controlliamo se si tratta di un numero Armstrong.
Dobbiamo calcolare la somma del cubo di ogni cifra. Quindi, inizializziamo la somma su 0 e otteniamo ogni numero di cifra utilizzando l'operatore modulo%. Il resto di un numero diviso per 10 è l'ultima cifra di quel numero. Prendiamo i cubi usando l'operatore esponente.
Infine, confrontiamo la somma con il numero originale e concludiamo che è il numero Armstrong se sono uguali.
Codice sorgente: controlla il numero Armstrong di n cifre
num = 1634 # Changed num variable to string, # and calculated the length (number of digits) order = len(str(num)) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp> 0: digit = temp % 10 sum += digit ** order temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number")
È possibile modificare il valore di num nel codice sorgente ed eseguire di nuovo per testarlo.