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)

Deletion in Singly Linked List in C++.

We have discussed Insertion and Searching a node in a singly Linked List in our previous post. In this post, we are going to discuss the Deletion of a node in a Linked List.


There are multiple situations of deleting a node from a linked list and these are:

  • Deletion of a node from the middle of the list.
Input: 3->8->1->2
Output: 3->8->2
  • Deletion of a node from the end of the list.
Input: 3->8->1->2
Output: 3->8->1
  • Deletion of a node from the beginning of the list.
Input: 3->8->1->2
Output: 8->1->2



Approach for Deletion of a node.

In a singly linked list, deletion is performed by modifying the pointers of the preceding and subsequent nodes to bypass the node to be deleted. Below are the steps to follow:
  • The deletion method takes integer data as an argument and searches the list for the node with the matching data. 
  • If the head node contains the data, the node is deleted and the head is updated to point to the next node. 
  • If the data is found in another node, the pointers of the preceding and subsequent nodes are modified to bypass the node to be deleted, and the node is deleted.

C++ Code to Delete a node from Singly Linked List.

//C++ Program to delete the node from a linked list
#include <iostream>
using namespace std;

struct Node {
  int data;
  Node *next;
};

class SinglyLinkedList {
private:
  Node *head;

public:
  SinglyLinkedList() : head(nullptr) {}

  void insert(int data) {
    Node *newNode = new Node;
    newNode->data = data;
    newNode->next = head;
    head = newNode;
  }

  void deleteNode(int data) {
    //when list is empty
    if (head == nullptr) return;
    //deleting first node of the list
    if (head->data == data) {
      Node *temp = head;
      head = head->next;
      delete temp;
      return;
    }
    //deleting middle or last node of the list
    Node *prev = head;
    Node *curr = head->next;
    while (curr != nullptr && curr->data != data) {
      prev = curr;
      curr = curr->next;
    }
    if (curr == nullptr) return;
    prev->next = curr->next;
    delete curr;
  }

  void printList() {
    Node *temp = head;
    while (temp != nullptr) {
      cout << temp->data << " ";
      temp = temp->next;
    }
    cout << std::endl;
  }
};

int main() {
  SinglyLinkedList list;

  list.insert(10);
  list.insert(20);
  list.insert(30);
  list.insert(40);
  list.insert(50);
  list.printList();
  list.deleteNode(30);
  list.printList();
  return 0;
}
Output:
50 40 30 20 10
50 40 20 10
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Types of Recursion in C++ with Examples

Recursion and its type in C++

Recursion is a process in which a function calls itself directly or indirectly to solve a problem. In this article, we will learn Recursion in C++ and its implementation.

Syntax:

int fun()
{
   ....
   fun()
}

Recursion allows the function to repeat a specific action until a specific condition is met and the function stops calling itself when the specific condition is met that stopping condition is also known as the base condition.  

Let's understand recursion with one standard example: finding the factorial of a given number. 

C++ Program to find the Factorial of a number.

#include<iostream>
using namespace std;

//function to find factorial
int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main()
{
    int num;

    cout<<"Enter a number: ";
    cin>>num;
    cout<<"Factorial of given number: "<<factorial(num);

    return 0;
}
Output:
Enter a number: 5
Factorial of given number: 120

Working of Recursion.

In the above example, the factorial function calculates the factorial of n by making a recursive call to itself with n-1 as the argument. The if statement checks for the base case, which is when n is equal to 0 and returns 1 in that case. When the base case is not reached, the function calculates n * factorial(n-1), and this continues until the base case is reached.
recursion working for factorial
Recursion

We need to follow two simple steps to solve any recursion problem and these are:

Step 1: Divide the problem into smaller sub-problem. 
Finding the solution for a smaller sub-problem is easy compared to finding the solution for a single large problem. In recursion, we keep dividing the problem into smaller sub-problem until we find the smallest sub-problem.

Step 2: Specify the base condition to stop the recursion.
The base condition is the one that doesn't require calling the same function again and it helps in stopping the recursion. In our case, finding the factorial of 0 is the base case. 

Types of Recursion.

  • Direct Recursion
  • Indirect Recursion
  • Tail Recursion
  • Non-Tail Recursion

1. Direct Recursion.

Direct recursion is a condition in which the function calls itself directly from the inside.
//Example of direct Recursion
void fun()
{
    //some code

    fun();

}


2. Indirect Recursion.

Indirect recursion is a condition in which the first function calls the second function and the second function again calls the first function.
//Example of indirect Recursion
void fun_1()
{
    //some code
    fun_2();
}

void fun_2()
{
    //some code
    fun_1();
}

3. Tail Recursion.

A recursion function is said to be a tail recursion if the recursion call is the last thing done by the function. There is no need to keep a record of the previous state.

Example: 
//Example of Tail Recursion in C++
#include<iostream>
using namespace std;

//recursive function
int fun(int n)
{
    if(n == 0)
      return 0;
    else
      cout<<n<<" ";
    return fun(n - 1);    
}
int main(){
    //function call
    fun(3);

    return 0;
}
Output:
3 2 1

4. Non-Tail Recursion.

A recursion function is said to be non-tail recursion when the same function call is not the last thing done by the function.  After returning back there is some statement left to evaluate. 

Example:
//Non-Tail Recursion Example in C++
#include<iostream>
using namespace std;

void fun(int n)
{
  if(n == 0)
    return;

  fun(n - 1);
  cout<<n<<" ";

}

int main()
{
  //function call
  fun(3);

  return 0;
}
Output:
1 2 3


Conclusion.

  • Every recursion program can be written as iterative.
  • Every recursion program can be modeled into an iterative program but recursive programs are more elegant and require relatively fewer lines of code.
  • The recursive program requires more space in memory than iterative programs.

DON'T MISS

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