Check the given number is armstrong or not | Python

Introduction

    An Armstrong number (also known as a narcissistic number, pluperfect digital invariant, or sometimes a plus perfect number) is a specific kind of number in mathematics. It is a number that is the sum of its own digits each raised to the power of the number of digits. In other words, an n-digit number is considered an Armstrong number if the sum of its digits, each raised to the power of n, is equal to the number itself. 

In this blog post, we'll explore what Armstrong numbers are and delve into a simple Python program that checks whether a given number is an Armstrong number or not.


Code

    
   
       // Program to check if a number is an Armstrong number |Python|
       # Python program to check if a number is an Armstrong number
 
       # Input from the user
       arm = int(input("Enter a number: "))
       
       # Initialize variables
       sum = 0
       temp = arm
       
       # Loop through each digit of the number
       while temp > 0:
           d = temp % 10
           sum += d ** 3
           temp //= 10
       
       # Check if the number is an Armstrong number
       if arm == sum:
           print(arm, "is an Armstrong number")
       else:
           print(arm, "is not an Armstrong number")
       
     
   


Output

    
       // Output
       Enter a number:153
 
       153 is an armstrong number      
     




Algorithm


 Input: Integer arm
 Output: Print whether arm is an Armstrong number or not
 
 1. Accept an integer input from the user and store it in a variable arm.
 2. Initialize Variables:
    - Set sum and temp to 0.
    - Copy the value of arm to temp.
 3. Loop through each digit:
    - While temp is greater than 0, repeat the following steps:
      - Extract the last digit of temp using the modulo operation and store it in variable d.
      - Add the cube of d to the sum.
      - Update temp by removing the last digit using integer division.
 4. Check for Armstrong Number:
    - If the original number arm is equal to the calculated sum, then the number is an Armstrong number.
      - Print that arm is an Armstrong number.
    - Otherwise, the number is not an Armstrong number.
      - Print that arm is not an Armstrong number.
  


Explanation

    We take input from the user, storing it in the variable 'arm'. Initialize 'sum' and 'temp' variables to 0 and the input number, respectively. The while loop extracts each digit of the number, cubes it, and adds it to 'sum'. Finally, we compare 'arm' with 'sum' to check if it's an Armstrong number. 

 This program utilizes basic arithmetic operations and looping to efficiently determine the Armstrong nature of a given number.

Post a Comment

0 Comments