avkLab

Narcissic Numbers

Jul 9th, 2022
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. #----------------------------------------------------------------------------
  4. # Created by  : Alain Van Kerckhoven
  5. # Created Date: 9 juillet 2022
  6. # Licence     : GPL
  7. # Version     : 1.0
  8. # ---------------------------------------------------------------------------
  9. """
  10. Soit un nombre de c chiffres. Un nombre narcissique est égal à la somme de
  11. ses chiffres à la puissance c.
  12. 153 a 3 chiffres et 153 = 1**3 + 5**3 + 3**3
  13. https://www.wikiwand.com/en/Narcissistic_number
  14. """
  15. # ---------------------------------------------------------------------------
  16.  
  17.  
  18. # Compter le nombre de chiffres d'un nombre
  19. def count_digit(n):
  20.     count = len(str(n))
  21.     return count
  22.  
  23.  
  24. # Vérifier si un nombre est narcissique
  25. def is_narcissic(n):
  26.     if n< 0:
  27.         return False
  28.    
  29.     n2 = n
  30.     narcissic_sum = 0
  31.     digit = count_digit(n)
  32.     while n:
  33.         remainder = n%10
  34.         narcissic_sum += remainder**digit
  35.         n //= 10
  36.  
  37.     return narcissic_sum == n2
  38.  
  39.  
  40. # Demander l'intervalle de recherche
  41. val_min = int(input("Valeur minimale : "))
  42. val_max = int(input("Valeur maximale : "))
  43.  
  44.  
  45. # Recherche des nombres narcissiques dans l'intervalle demandé
  46. print("Les nombres narcissiques de", val_min,"à",val_max,"sont :")
  47. for i in range(val_min, val_max+1):
  48.     if is_narcissic(i):
  49.         print(i, end=" ")
  50.  
Advertisement
Add Comment
Please, Sign In to add comment