Python Program to Add Digits of a Number.

Given a number num, write a Python program to add digits of the given number and print the sum as an output.

Example:

Input: num = 145
Output: 10

Explanation: 1 + 4 + 5 = 10

Input: num = 9231
Output: 15

Explanation: 9 + 2 + 3 + 1 = 15

There are multiple approaches by which we can solve this problem, let's discuss each of them one by one.

Approach 1: Using integer division and modulo operator.

In this approach, we use the modulo operator % to extract the last digit of the number and add it to the sum variable. We then use integer division // to remove the last digit from the number and repeat the process until the number becomes zero.

Python code:
# Python program to add digits of a number
def add_digits(n):
    sum = 0
    while n > 0:
        sum += n % 10
        n = n // 10
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 123
6
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 2: Using string conversion and for loop.

In this approach, we first convert the number to a string and then use a for loop to iterate over each character in the string. We convert each character back to an integer and add it to the sum variable.

Python code:
# Python program to add digits of a number
def add_digits(n):
    n = str(n)
    sum = 0
    for digit in n:
        sum += int(digit)
    return sum

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 4753
19
  • Time Complexity: O(number of digits)
  • Space Complexity: O(1)

Approach 3: Using Recursion.

In this approach, we use recursion, to sum up, the digits of the number. The base case is when the number becomes zero, in which case we return zero. Otherwise, we extract the last digit using the modulo operator and add it to the result of the recursive call to add_digits with the number divided by 10.

Python Code:
# Python program to add digits of a number
def add_digits(n):
    if n == 0:
        return 0
    return n % 10 + add_digits(n // 10)

# take input from the user
num = int(input("Enter a number: "))  

print(add_digits(num))    
Output:
Enter a number: 542
11
  • Time Complexity: O(number of digits)
  • Space Complexity: O(n) 

Read more:

Python Program to Reverse a Number.

Given a number num, you need to write a Python Program to print the number in reverse. 

Example:

Input: num = 1372
Output: 2731

Input: num = 901
Output: 109

There are multiple approaches to solving this problem, let's discuss each of them one by one:

Reverse a number using String Slicing in Python.

Python slicing technique is one important feature that is used for extracting a portion of a string, a list of tuples. We can use this notation to reverse the given number.

Steps to do so:
  • The function takes the input num and converts it to a string.
  • The function then uses slicing to reverse the string and returns the result as an integer.
  • The program then takes input from the user and stores it in the num variable.
Python Code:
def reverse_number(num):
    return int(str(num)[::-1])

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 1348
The reversed number is 8431


Reverse a number using a while loop in Python.

We can use any loop to iterate through each digit of the given number and perform some mathematical operations to reverse their order and generate a new reverse number. 

Steps to do so:
  • The program defines a function reverse_number to reverse a given number.
  • The function initializes two variables rev and rem to store the reversed number and the remainder of the number.
  • The function then uses a while loop to reverse the number digit by digit.
  • In each iteration, the function calculates the remainder of the number by dividing it by 10 and stores it in rem.
  • The function then multiplies the current value of rev by 10 and adds rem to it.
  • The function then updates the value of num by dividing it by 10.
  • The function repeats these steps until num is 0.
Python Code:
def reverse_number(num):
    rev = 0
    while num > 0:
        rem = num % 10
        rev = rev * 10 + rem
        num = num // 10
    return rev

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 034
The reversed number is 43


Reverse a number using Recursion in Python.

This approach is the same as the previous one, In this approach, we are using recursion to iterate through each digit of the given number.
 
Steps to do so:
  • The function takes two inputs: num and rev, where num is the number to be reversed and rev is the reversed number so far.
  • The function uses an if statement to check if num is 0. If num is 0, the function returns rev.
  • If num is not 0, the function calculates the remainder of num by dividing it by 10 and stores it in rem.
  • The function then calls itself with num // 10 and rev * 10 + rem as inputs and returns the result.
Python Code:
def reverse_number(num, rev=0):
    if num == 0:
        return rev
    rem = num % 10
    return reverse_number(num // 10, rev * 10 + rem)

# take input from the user
num = int(input("Enter a number: "))

# reverse the number
rev = reverse_number(num)

# print the reversed number
print("The reversed number is", rev)
Output:
Enter a number: 2034
The reversed number is 4302
  • Time Complexity: O(n) where n is the number of digits that the number contains.
  • Space Complexity: O(n) stack space is required for performing recursion.

Python Program to Check Armstrong Number.

Given a number x, write a Python program to check whether the given number is an Armstrong number or not. 

An Armstrong number, also known as a narcissistic number or a pluperfect digital invariant, is a number that is equal to the sum of its own digits raised to the power of the number of digits. ()


For example, the number 153 is an Armstrong number because 1^3 + 5^3 + 3^3 = 153.

Example:

Input: num = 1634
Output: 1634 is an Armstrong Number.

Explanation: 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634

Input: num = 130
Output: 130 is not an Armstrong Number.

Explanation: 1*1*1 + 3*3*3 + 0*0*0 = 28


Python Program to check if the given number is Armstrong Number.

def is_armstrong_number(number):
    # convert the number to a string and find the number of digits
    num_str = str(number)
    num_digits = len(num_str)

    # initialize a variable to store the sum of the digits raised to the power of the number of digits
    sum_of_digits = 0

    # loop through each digit in the number
    for digit in num_str:
        # raise the digit to the power of the number of digits and add it to the sum
        sum_of_digits += int(digit) ** num_digits

    # return True if the sum is equal to the number, and False otherwise
    return sum_of_digits == number

# take input from the user
number = int(input("Enter a number: "))

# check if the number is an Armstrong number
if is_armstrong_number(number):
    print(number, "is an Armstrong number.")
else:
    print(number, "is not an Armstrong number.")
Output:
Enter a number: 153
153 is an Armstrong number.
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
Code Explanation
  • The program defines a function is_armstrong_number to check if a given number is an Armstrong number.
  • The function first converts the number to a string and finds the number of digits by finding the length of the string.
  • The function then initializes a variable sum_of_digits to store the sum of the digits raised to the power of the number of digits.
  • The function then loops through each digit in the number, raises the digit to the power of the number of digits, and adds the result to the sum_of_digits.
  • The function then returns True if the sum_of_digits is equal to the original number, and False otherwise.

Read More:

Python Program to Find Compound Interest.

In this article, we will discuss Python code for calculating Compound Interest. But before moving to the code section let us understand the process of calculating Compound Interest.


What is Compound Interest?

Compound Interest is the interest calculated on the original principal of a loan or deposit, as well as on the accumulated interest of previous periods. This means that the interest earned in a given period is added to the principal, and the interest for the next period is calculated based on the increased principal. This results in a faster accumulation of interest over time compared to simple interest.


The formula for calculating compound interest is: Compound Interest = Principal * (1 + Rate / n)^(nt)

  • The principal is the original amount of the loan or deposit.
  • Rate is the interest rate, expressed as a decimal.
  • n is the number of times the interest is compounded in a year.
  • t is the number of years for which the loan or deposit is held.

For example, if you deposit $1000 at an interest rate of 5% compounded annually for 2 years, the compound interest earned would be $1000 * (1 + 0.05 / 1)^(2 * 1) = $1050.25.


Python Program to calculate the Compound Interest.

def compound_interest(principal, rate, n, t):
    return principal * (1 + rate / n) ** (n * t)

# take input for the principal, rate, number of times compounded, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
n = float(input("Enter the number of times the interest is compounded per year: "))
t = float(input("Enter the time period (in years): "))

# convert the interest rate from a percentage to a decimal
rate = rate / 100

# calculate the compound interest
interest = compound_interest(principal, rate, n, t) - principal

# print the result
print("The compound interest is", interest)
Output:
Enter the principal amount: 150000
Enter the rate of interest: 8
Enter the number of times the interest is compounded per year: 7
Enter the time period (in years): 6
The compound interest is 91752.18133848405
  • Time Complexity: O(1)
  • Space Complexity: O(1)
Read more:

Python Program to Find Simple Interest.

This article will discuss the Python Program to calculate Simple Interest. But before understanding Python Code, let us first understand the process of calculating Simple Interest. 


What is Simple Interest?

Simple Interest is the interest calculated on the original amount (also known as the principal) of a loan or deposit, without taking into account any interest earned on the interest. It is calculated as a percentage of the principal and the time period for which the loan or deposit is held.


The formula for calculating simple interest is: Simple Interest = (Principal * Rate * Time) / 100

  • The principal is the original amount of the loan or deposit.
  • Rate is the interest rate, expressed as a percentage.
  • Time is the time period for which the loan or deposit is held, expressed in years.

For example, if you deposit $1000 at an interest rate of 5% for 2 years, the simple interest earned would be $1000 * 5 * 2 / 100 = $100.


Python Programs for Calculating Simple Interest.

Approach 1: Python code using Formula.

# take input for the principal, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period (in years): "))

# calculate the interest using the formula
interest = principal * rate * time / 100

# print the result
print("The interest is", interest)
Output:
Enter the principal amount: 2000
Enter the rate of interest: 5
Enter the time period (in years): 10
The interest is 1000.0


Approach 2: Python Code using a Function.

def simple_interest(principal, rate, time):
    return principal * rate * time / 100

# take input for the principal, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period (in years): "))

# calculate the interest using the function
interest = simple_interest(principal, rate, time)

# print the result
print("The interest is", interest)
Output:
Enter the principal amount: 5000
Enter the rate of interest: 10
Enter the time period (in years): 5
The interest is 2500.0


Approach 3: Python Code using Lambda Function.

# define a lambda function to calculate the simple interest
simple_interest = lambda p, r, t: p * r * t / 100

# take input for the principal, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period (in years): "))

# calculate the interest using the lambda function
interest = simple_interest(principal, rate, time)

# print the result
print("The interest is", interest)
Output:
Enter the principal amount: 25000
Enter the rate of interest: 7
Enter the time period (in years): 5
The interest is 8750.0

Python Program to Check a Prime Number.

Given a number num, write a python program to check if the given number is prime or not. If the number is prime then print true else print false.

Prime Numbers are whole numbers that are not divisible by any other whole number other than itself and 1.(e.g. 2, 3, 5, 7, 11, etc) (alert-success)

Example:

Input: num = 11
Output: True

Input: num = 9
Output: False

Approach 1: Check Prime using a for loop.

In this approach, the program uses a for loop to check if the number is divisible by any number other than 1 and itself. If it is divisible by any such number, the flag is_prime is set to False, and the loop is broken.

Python Program:
# take input for the number
num = int(input("Enter a number: "))

# initialize a flag to check if the number is prime
is_prime = True

# use a for loop to check if the number is divisible by any other number
for i in range(2, num):
    if num % i == 0:
        is_prime = False
        break

# print the result
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")
Output:
Enter a number: 11
11 is a prime number
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Approach 2: Check Prime using the sqrt function.

In this approach, the program uses the sqrt() function from the math module to only check for divisibility up to the square root of the number. This speeds up the program as the number of iterations is reduced.

Python Code:
# import the sqrt function from the math module
from math import sqrt

# take input for the number
num = int(input("Enter a number: "))

# initialize a flag to check if the number is prime
is_prime = True

# use a for loop to check if the number is divisible by any other number up to its square root
for i in range(2, int(sqrt(num)) + 1):
    if num % i == 0:
        is_prime = False
        break

# print the result
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")
Output:
Enter a number: 7
7 is a prime number
  • Time Complexity: O(sqrt(n))
  • Space Complexity: O(1)

Approach 3: Check Prime using a while loop.

In this approach, the program uses a while loop to check for divisibility in a similar way as the for loop in approach 1.

Python Code:
# take input for the number
num = int(input("Enter a number: "))

# initialize a flag to check if the number is prime
is_prime = True

# initialize the counter to 2
i = 2

# use a while loop to check if the number is divisible by any other number
while i < num:
    if num % i == 0:
        is_prime = False
        break
    i += 1

# print the result
if is_prime:
    print(num, "is a prime number")
else:
    print(num, "is not a prime number")
Output:
Enter a number: 10
10 is not a prime number
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Python Program to Find Factorial of a Number.

Given a number num, write a Python program to find the factorial of that number. The Factorial of a non-negative number is equal to the multiplication of all integers smaller than or equal to that number. 

Example:
Input: num = 5
Output: 120

Explanation: 5*4*3*2*1 = 120

Input: num = 0
Output: 1

Input: num = 7
Output: 5040

Explanation: 7*6*5*4*3*2*1 = 5040


Approach 1: Factorial of a number using a for a loop.

In this approach, the program uses a for loop to iterate through the numbers from 1 to the given number and calculates the factorial by multiplying each number.

Python Code:
# take input for the number
num = int(input("Enter a number: "))

# initialize the factorial to 1
factorial = 1

# use a for loop to calculate the factorial
for i in range(1, num + 1):
    factorial *= i

# print the result
print("The factorial of", num, "is", factorial)
Output:
Enter a number: 5
The factorial of 5 is 120
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Approach 2: Factorial of a number using Recursion.

In this approach, the program uses recursion to find the factorial. The factorial function calls itself with the argument n-1 until the base case n=1 is reached, and then returns the result.

Python Code:
# define a recursive function to find the factorial
def factorial(n):
    if n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# take input for the number
num = int(input("Enter a number: "))

# call the factorial function to find the factorial
result = factorial(num)

# print the result
print("The factorial of", num, "is", result)
Output:
Enter a number: 5
The factorial of 5 is 120
  • Time Complexity: O(n)
  • Space Complexity: O(n)

Approach 3: Factorial of a number using a While loop.

In this approach, the program uses a while loop to calculate the factorial in a similar way as the for loop in approach 1.

Python Code:
# take input for the number
num = int(input("Enter a number: "))

# initialize the factorial to 1
factorial = 1

# initialize the counter to 1
i = 1

# use a while loop to calculate the factorial
while i <= num:
    factorial *= i
    i += 1

# print the result
print("The factorial of", num, "is", factorial)
Output:
Enter a number: 7
The factorial of 7 is 5040
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Related Articles:

Python Program to Find the Maximum of Two Numbers.

Given two numbers num1 and num2, write a Python program to find the maximum of two numbers.

Example:
Input: num1 = 10, num2 = 15
Output: 15

Input: num1 = -5, num2 = -2
Output: -2

Approach 1: Comparing two numbers using the if..else statement.

Explanation:
  • In the first two lines, the program takes input for two numbers.
  • In the next few lines, the program uses an if statement to compare the two numbers and find the maximum.
  • Finally, the program prints the result.
Python Example Code:
# take input for the two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# compare the two numbers and find the maximum
if num1 > num2:
    maximum = num1
else:
    maximum = num2

# print the result
print("The maximum number is", maximum)
Output:
Enter first number: 10
Enter second number: 15
The maximum number is 15
  • Time Complexity: O(1)
  • Space Complexity: O(1)

Approach 2: Using the max() function. This function returns the maximum of the values passed as its arguments.

Explanation:
  • The first two lines are the same, taking input for the two numbers.
  • In the next line, the program uses the max() function to find the maximum of the two numbers.
  • Finally, the program prints the result.
Python Example Code:
# take input for the two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# use the max function to find the maximum of the two numbers
maximum = max(num1, num2)

# print the result
print("The maximum number is", maximum)
Output:
Enter first number: -10
Enter second number: -15
The maximum number is 10
  • Time Complexity: O(1)
  • Space Complexity: O(1)

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson