Python

Program to Take in the Marks of 5 Subjects and Display the Grade

Python Program to Take in the Marks of 5 Subjects and Display the Grade

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Given the marks of 5 subjects of the student, the task is to display the grade of the student based on the marks in

Python.

Examples:

Example1:

Input:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63

Output:

Average of 5 marks = 72.8 Grade =C

Example2:

Input:

Enter first subject marks as integer = 63
Enter second subject marks as integer = 19
Enter third subject marks as integer = 99
Enter fourth subject marks as integer = 85
Enter fifth subject marks as integer = 73

Output:

Average of 5 marks = 67.8 Grade =D

Program to Take in the Marks of 5 Subjects and Display the Grade in Python

There are several ways to calculate the grade of the student based on the marks of 5 subjects in Python some of them are:

Method #1:Using IF..elif..else Statements(Static Input)

Approach:

  • Give the 5 subject marks as static input and store them in 5 variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as static input and store them in 5 variables.
marks1 = 95
marks2 = 85
marks3 = 89
marks4 = 93
marks5 = 87
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Average of 5 marks = 89.8 Grade =B

Explanation:

  • The user must enter 5 different values as static input and store them in different variables.
  • Then add together all five marks and divide by five to get the average.
  • If the average is more than 90, the grade is displayed as “A.”
  • If the average is between 80 and 90, the letter “B” is printed.
  • If the average is between 70 and 80, the letter “C” is printed.
  • If the average is between 60 and 70, the letter “D” is printed.
  • If the average falls below 60, the letter “F” is printed.

Method #2:Using IF..elif..else Statements (User Input separated by newline)

Approach:

  • Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
# Store them in 5 separate variables.
marks1 = int(input('Enter first subject marks as integer = '))
marks2 = int(input('Enter second subject marks as integer = '))
marks3 = int(input('Enter third subject marks as integer = '))
marks4 = int(input('Enter fourth subject marks as integer = '))
marks5 = int(input('Enter fifth subject marks as integer = '))
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63
Average of 5 marks = 72.8 Grade =C

Method #3:Using IF..elif..else Statements and map(),split() functions (User Input separated by spaces)

Approach:

  • Give the 5 subject marks as user input separated by spaces using map(), split() functions.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input separated by spaces using map(), split() functions.
# Store them in 5 separate variables.
marks1, marks2, marks3, marks4, marks5 = map(int, input(
    'Enter 5 subject marks separated by spaces = ').split())
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter 5 subject marks separated by spaces = 45 96 78 99 92
Average of 5 marks = 82.0 Grade =B

Related Programs:

Python Program to Take in the Marks of 5 Subjects and Display the Grade Read More »

Program to Find the Smallest Divisor of an Integer

Python Program to Find the Smallest Divisor of an Integer

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Given a number, the task is to find the smallest number which divides the given number in Python.

Examples:

Example1:

Input:

given number = 91

Output:

The smallest which divides the given number [ 91 ] = 7

Example2:

Input:

given number = 169

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Program to Find the Smallest Divisor of an Integer in Python

There are several ways to find the smallest divisor of the given number in Python some of them are:

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 91
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

The smallest which divides the given number [ 91 ] = 7

Method #2: Using for loop(User Input )

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

Enter some random number = 369
The smallest which divides the given number [ 369 ] = 3

Explanation:

  • The user must enter a number.
  • The for loop has a range of 2 to the number
  • If the remainder of the number is zero when divided by the value of i the element is a divisor of the number.
  • Print the number and break the loop.

Method #3:Using While Loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 125
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

The smallest which divides the given number [ 125 ] = 5

Method #4:Using While Loop(User Input)

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

Enter some random number = 578
The smallest which divides the given number [ 578 ] = 2

Method #5:Using List Comprehension

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Using List Comprehension, for loop and if statements add all the divisors of the given number from 2 to given number into the list.
  • Print the first element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Using List Comprehension, for loop and if statements add
# all the divisors of the given number
# from 2 to given number into the list.
divList = [numbe for numbe in range(2, gvnNumb+1) if(gvnNumb % numbe == 0)]
smalldivi = divList[0]
# Print the first element in the given list.
print('The smallest which divides the given number [', gvnNumb, '] =', smalldivi)

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Related Programs:

Python Program to Find the Smallest Divisor of an Integer Read More »

Program Divide all Elements of a List by a Number

Python Program Divide all Elements of a List by a Number

In the previous article, we have discussed Python Program to Get Sum of all the Factors of a Number

Given a list, and the task is to divide all the elements of a given List by the given Number in Python

As we know, elements such as int, float, string, and so on can be stored in a List. As we all know, dividing a string by a number is impossible. To divide elements of a list, all elements must be int or float.

Examples:

Example1:

Input:

Given List = [3, 2.5, 42, 24, 15, 32]
Given Number = 2

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Example 2:

Input:

Given List =  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Given Number = 5

Output:

The above given list after division all elements of a List by the given Number= [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

Program Divide all Elements of a List by a Number

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Below are the ways to divide all Elements of a List by a Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_Lst = [3, 2.5, 42, 24, 15, 32]
# Give the number as static input and store it in another variable.
gvn_numb = 2
# Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator  by  the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using the For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • Print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

#Give the list as user input using list(),map(),input(),and split() functions.
gven_Lst = list(map(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
gvn_numb = int(input("Enter some random number = " ))
#Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator by the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

Enter some random List Elements separated by spaces = 4 5 8 9.6 15 63 32 84
Enter some random number = 4
The above given list after division all elements of a List by the given Number= [1.0, 1.25, 2.0, 2.4, 3.75, 15.75, 8.0, 21.0]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program Divide all Elements of a List by a Number Read More »

Program for Exponential Squaring (Fast Modulo Multiplication)

Python Program for Exponential Squaring (Fast Modulo Multiplication)

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Given two numbers base value and the exponential value, the task is to find the power of base and exponent modular 10^9+7

Examples:

Example1:

Input:

Given base value =  5
Given exponent value = 3

Output:

The value of the power of base and exponent modular 10^9+7 =  125

Example2:

Input:

Given base value =  3
Given exponent value = 10000

Output:

The value of the power of base and exponent modular 10^9+7 =  895629451

Program for Exponential Squaring (Fast Modulo Multiplication) in Python

Below are the ways to find the power of base and exponent modular 10^9+7 for the given base and exponential values:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the base value as static input and store it in a variable.
  • Give the exponential value as static input and store it in another variable.
  • Pass the given base and exponential values as the arguments to the exponentl_squaring() function and store it in a variable.
  • Take a variable to say numb and initialize its value with 1000000007(10^9+7).
  • Create a function to say exponentl_squaring() which takes the given two base and exponential values as the arguments and returns the value of the power of base and exponent modular 10^9+7.
  • Inside the function, take a variable say p, and initialize its value to 1.
  • Loop until the given exponential value is greater than 0 using the while loop.
  • Check if the given exponential value is odd using the if conditional statement.
  • If it is true, multiply p with the given base value and store it in another variable.
  • Calculate the value of the above result modulus numb(10^9+7) and store it in the same variable p.
  • Multiply the given base value with itself and apply the modulus operator with 10^9+7(numb).
  • Store it in the same variable given base value.
  • Divide the given exponential value by 2 and convert it to an integer using the int() function.
  • Store it in the same variable given exponential value.
  • Return the value of p modulus 10^9+7.
  • Print the value of the power of base and exponent modular 10^9+7.
  • The Exit of the Program.

Below is the implementation:

# Take a variable to say numb and initialize its value with 1000000007(10^9+7).
numb = 1000000007

# Create a function to say exponentl_squaring() which takes the given two base and
# exponential values as the arguments and returns the value of the power of base and
# exponent modular 10^9+7.


def exponentl_squaring(gvn_baseval, gvn_exponentlval):
  # Inside the function, take a variable say p, and initialize its value to 1.
    p = 1
    # Loop until the given exponential value is greater than 0 using the while loop.
    while(gvn_exponentlval > 0):
           # Check if the given exponential value is odd using the if conditional statement.
        if (gvn_exponentlval % 2 != 0):
            # If it is true, multiply p with the given base value and store it in another
            # variable.
            k = p * gvn_baseval
            # Calculate the value of the above result modulus numb(10^9+7) and store it in the
            # same variable p.
            p = k % numb
      # Multiply the given base value with itself and apply the modulus operator with
      # 10^9+7(numb).
      # Store it in the same variable given base value.
        gvn_baseval = (gvn_baseval * gvn_baseval) % numb
        # Divide the given exponential value by 2 and convert it to an integer using the
        # int() function.
        # Store it in the same variable given exponential value.
        gvn_exponentlval = int(gvn_exponentlval / 2)
   # Return the value of p modulus 10^9+7.
    return p % numb


# Give the base value as static input and store it in a variable.
gvn_baseval = 5
# Give the exponential value as static input and store it in another variable.
gvn_exponentlval = 3
# Pass the given base and exponential values as the arguments to the exponentl_squaring()
# function and store it in a variable.
rslt = exponentl_squaring(gvn_baseval, gvn_exponentlval)
# Print the value of the power of base and exponent modular 10^9+7.
print("The value of the power of base and exponent modular 10^9+7 = ", rslt)

Output:

The value of the power of base and exponent modular 10^9+7 =  125

Method #2: Using While loop (User Input)

Approach:

  • Give the base value as user input using the int(input()) function and store it in a variable.
  • Give the exponential value as user input using the int(input()) function and store it in another variable.
  • Pass the given base and exponential values as the arguments to the exponentl_squaring() function and store it in a variable.
  • Take a variable to say numb and initialize its value with 1000000007(10^9+7).
  • Create a function to say exponentl_squaring() which takes the given two base and exponential values as the arguments and returns the value of the power of base and exponent modular 10^9+7.
  • Inside the function, take a variable say p, and initialize its value to 1.
  • Loop until the given exponential value is greater than 0 using the while loop.
  • Check if the given exponential value is odd using the if conditional statement.
  • If it is true, multiply p with the given base value and store it in another variable.
  • Calculate the value of the above result modulus numb(10^9+7) and store it in the same variable p.
  • Multiply the given base value with itself and apply the modulus operator with 10^9+7(numb).
  • Store it in the same variable given the base value.
  • Divide the given exponential value by 2 and convert it to an integer using the int() function.
  • Store it in the same variable given exponential value.
  • Return the value of p modulus 10^9+7.
  • Print the value of the power of base and exponent modular 10^9+7.
  • The Exit of the Program.

Below is the implementation:

# Take a variable to say numb and initialize its value with 1000000007(10^9+7).
numb = 1000000007

# Create a function to say exponentl_squaring() which takes the given two base and
# exponential values as the arguments and returns the value of the power of base and
# exponent modular 10^9+7.


def exponentl_squaring(gvn_baseval, gvn_exponentlval):
  # Inside the function, take a variable say p, and initialize its value to 1.
    p = 1
    # Loop until the given exponential value is greater than 0 using the while loop.
    while(gvn_exponentlval > 0):
           # Check if the given exponential value is odd using the if conditional statement.
        if (gvn_exponentlval % 2 != 0):
            # If it is true, multiply p with the given base value and store it in another
            # variable.
            k = p * gvn_baseval
            # Calculate the value of the above result modulus numb(10^9+7) and store it in the
            # same variable p.
            p = k % numb
      # Multiply the given base value with itself and apply the modulus operator with
      # 10^9+7(numb).
      # Store it in the same variable given base value.
        gvn_baseval = (gvn_baseval * gvn_baseval) % numb
        # Divide the given exponential value by 2 and convert it to an integer using the
        # int() function.
        # Store it in the same variable given exponential value.
        gvn_exponentlval = int(gvn_exponentlval / 2)
   # Return the value of p modulus 10^9+7.
    return p % numb

# Give the base value as user input using the int(input()) function and store it in a variable.
gvn_baseval = int(input("Enter some random number = "))
# Give the exponential value as user input using the int(input()) function and 
# store it in another variable.
gvn_exponentlval = int(input("Enter some random number = "))
# Pass the given base and exponential values as the arguments to the exponentl_squaring()
# function and store it in a variable.
rslt = exponentl_squaring(gvn_baseval, gvn_exponentlval)
# Print the value of the power of base and exponent modular 10^9+7.
print("The value of the power of base and exponent modular 10^9+7 = ", rslt)

Output:

Enter some random number = 3
Enter some random number = 10000
The value of the power of base and exponent modular 10^9+7 = 895629451

Python Program for Exponential Squaring (Fast Modulo Multiplication) Read More »

Python Program for Double Factorial

In the previous article, we have discussed Python Program for Product of Maximum in First array and Minimum in Second
Factorial:

The product of all positive integers less than or equal to n is the factorial of a non-negative integer n, denoted by n! in mathematics:

n! = n * (n – 1) *(n – 2) * . . . . . . . . . . 3 * 2 * 1.

4 != 4 * 3 * 2 *1=24

Double Factorial:

The product of all the integers from 1 to n with the same parity (odd or even) as n is the double factorial of a non-negative integer n. It is also known as a number’s semi factorial and is denoted by!!.

For example, the double factorial of 7 is 7*5*3*1 = 105

It is worth noting that as a result of this definition, 0!! = 1.

The double factorial for even number ‘n’ is:

n!!=prod_{k=1}^{n/2}(2k)=n(n-2)(n-4).....4*2

The double factorial for odd number ‘n’ is:

n!!=prod_{k=1}^{{n+1}/2}(2k-1)=n(n-2)(n-4).....3*1

Given a number ‘n’ and the task is to find the double factorial of a given number.

Examples:

Example 1:

Input:

Given number = 5

Output:

The double factorial of a given number{ 5 } =  15

Example 2:

Input:

Given number = 10

Output:

The double factorial of a given number{ 10 } =  3840

Program for Double Factorial in Python

Below are the ways to find the double factorial of a given number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘c’.
  • Loop from the given number to 0 in decreasing order with the stepsize of -2 using the for loop.
  • Inside the loop multiply the above initialized variable c with the iterator value and store it in the same variable ‘c’.
  • Print the double factorial of a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numbr = 8
# Take a variable, initialize it with the value '1', and store it in another
# variable say 'c'.
c = 1
# Loop from the given number to 0 in decreasing order with the stepsize of -2
# using the for loop.
for i in range(numbr, 0, -2):
    # Inside the loop multiply the above initialized variable c with the iterator value
    # and store it in the same variable 'c'.
    c *= i
 # Print the double factorial of a given number.
print("The double factorial of a given number{", numbr, "} = ", c)

Output:

The double factorial of a given number{ 8 } =  384

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘c’.
  • Loop from the given number to 0 in decreasing order with the stepsize of -2 using the for loop.
  • Inside the loop multiply the above initialized variable c with the iterator value and store it in the same variable ‘c’.
  • Print the double factorial of a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
numbr = int(input("Enter a random number = "))
# Take a variable, initialize it with the value '1', and store it in another
# variable say 'c'.
c = 1
# Loop from the given number to 0 in decreasing order with the stepsize of -2
# using the for loop.
for i in range(numbr, 0, -2):
    # Inside the loop multiply the above initialized variable c with the iterator value
    # and store it in the same variable 'c'.
    c *= i
 # Print the double factorial of a given number.
print("The double factorial of a given number{", numbr, "} = ", c)

Output:

Enter a random number = 7
The double factorial of a given number{ 7 } = 105

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program for Double Factorial Read More »

Program to Compute Prime Factors of an Integer

Python Program to Compute Prime Factors of an Integer

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

In this post, we’ll look at a Python program that prints out all the prime factors of a given number. A number is considered to be a prime factor of another number if it is a prime number and perfectly divides the given number. In this section, we will look at what a prime factor is, how to discover a prime factor, and the python program.

A number’s prime factors are the prime numbers that, when multiplied together, give the number. Two conditions can be used to determine a number’s prime factor:

The digit should be a prime number.

The number should perfectly divide the number.

Examples:

Example1:

Input:

given number =240

Output:

The prime factors of the given number are : 
2
3
5

Example2:

Input:

given number =33

Output:

Enter some random number = 33
The prime factors of the given number are : 
3
11

Program to Compute Prime Factors of an Integer in Python

There are several ways to compute prime factors of an integer in python some of them are:

Method #1: Using while loop (Static Input)

Approach:

  • Give the integer value as static input.
  • Using a while loop, first determine the number’s components.
  • Calculate whether the factors are prime or not using another while loop within the previous one.
  • Exit of program.

Below is the implementation:

# given number
numb = 240
# Printing the prime factors
print("The prime factors of the given number are : ")
value = 1
while(value <= numb):
    k = 0
    if(numb % value == 0):
        j = 1
        while(j <= value):
            if(value % j == 0):
                k = k+1
            j = j+1
        if(k == 2):
          # printing the prime factor
            print(value)
    # incremeent the value by 1
    value = value+1

Output:

The prime factors of the given number are : 
2
3
5

Explanation:

  • Given the number as static input.
  • The while loop is utilized, and the integer factors are obtained by using the modulus operator and determining whether the remainder of the number divided by value is zero.
  • The integer’s factors are then checked again to see if they are prime.
  • The factor of an integer is prime if it has two factors.
  • The integer’s prime factor is printed.

Method #2: Using while loop (User Input)

Approach:

  • Scan the number using int(input()) function.
  • Using a while loop, first determine the number’s components.
  • Calculate whether the factors are prime or not using another while loop within the previous one.
  • Exit of program.

Below is the implementation:

# Scan the number using int(input()) function.
numb = int(input("Enter some random number = "))
# Printing the prime factors
print("The prime factors of the given number are : ")
value = 1
while(value <= numb):
    k = 0
    if(numb % value == 0):
        j = 1
        while(j <= value):
            if(value % j == 0):
                k = k+1
            j = j+1
        if(k == 2):
          # printing the prime factor
            print(value)
    # incremeent the value by 1
    value = value+1

Output:

Enter some random number = 220
The prime factors of the given number are : 
2
5
11

Method #3:Efficient Method (User input)

Approach:

  • Scan the given number using int(input()) function.
  • We will print 2 and divide numb by 2 while it is divisible by 2.
  • Following step 2, numb must always be odd.
  • Begin a loop with I = 3 and work your way up to the square root of n. If I divide numb by I print I and divide numb by i. If we  unable to divide numb , increase the I value by 2 and proceed.
  • If numb is a prime number and higher than 2, it cannot be reduced to 1.
  • So, if numb is larger than 2, print it.

Below is the implementation:

import math
# Scan the number using int(input()) function.
numb = int(input("Enter some random number = "))
# Printing the prime factors
print("The prime factors of the given number are : ")
while numb % 2 == 0:
      print(2),
      numb = numb / 2

   # n became odd
for i in range(3,int(math.sqrt(numb))+1,2):
    while (numb % i == 0):
        print (int(i))
        numb = numb / i
    
if numb > 2:
    print (int(numb))

Output:

Enter some random number = 33
The prime factors of the given number are : 
3
11

Related Programs:

Python Program to Compute Prime Factors of an Integer Read More »

Program to Calculate the HCF

Python Program to Calculate the HCF/GCD

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Highest Common Factor (HCF) / Greatest Common Divisor (GCD) :

When at least one of the integers is not zero, the greatest positive integer that evenly divides the numbers without a remainder is called the Highest Common Factor or Greatest Common Divisor.

The GCD of 12 and 16 is, for example, 4.

Given two numbers the task is to find the highest common factor of the two numbers in Python.

Examples:

Example1:

Input:

a= 24   b=36

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Example2:

Input:

a= 18 b=72

Output:

The Highest Common Factor (HCF) of the numbers 18 72 = 18

Example3:

Input:

a= 4 b=8

Output:

The Highest Common Factor (HCF) of the numbers 4 8 = 4

Example4:

Input:

a= 9 b=9

Output:

The Highest Common Factor (HCF) of the numbers 9 9 = 9

Explanation:

 The Highest common factor of two numbers is number itself if both the numbers are equal

Python Program to Calculate the HCF/GCD

There are several ways to calculate the hcf of the two numbers in python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using loops

Below is the implementation:

# function which computes and returns the highest common factor of the given two numbers
def findGcd(number1, number2):

    # finding the smaller number
    if number1 > number2:
        smallNumber = number2
    else:
        smallNumber = number1
    # using for loop to traverse from 1 to smaller number
    for i in range(1, smallNumber+1):
      # if it divides the given two numbers without leaving the
      # remainder then assign result it with that loop iterator value
        if((number1 % i == 0) and (number2 % i == 0)):
            result = i
    # return the final result which is greatest common divisor(GCD)
    return result


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation:

The findGcd() function is called with two integers stored in variables number1 and number2. The function computes and returns the H.C.F. of these two integers.

Because the H.C.F can only be less than or equal to the lowest number, we first find the smaller of the two integers in the function. Then, to move from 1 to that number, we utilize a for loop.

We check if our number divides both input numbers precisely in each cycle. If this is the case, the number is saved as H.C.F. We wind up with the greatest integer that divides both numbers properly at the end of the loop.

The method described above is simple to learn and apply, but it is inefficient. The Euclidean algorithm is a significantly more efficient technique of calculating the H.C.F.

Method #2:Using Euclidean algorithm

This approach is based on the fact that the H.C.F. of two numbers also divides their difference.

We divide the greater by the smaller and take the remainder in this algorithm. Divide the smaller number by the remainder. Repeat until the residual equals zero.

Facts of Euclidean Algorithm:

GCD does not change when we subtract a smaller number from a larger number (we reduce a larger number). So, if we keep subtracting the largest of two numbers, we get GCD.
Instead of subtracting, we can divide the smaller integer, and the procedure will terminate when we find a remainder of zero.

Algorithm:

  1. Let number1 and number2 be the two numbers in the pseudocode of the algorithm.
  2. number1 mod number2 =R
  3. Assume that number1= number2 and number2 = R.
  4. Continue with Steps 2 and 3 until number1 mod number2 is greater than 0.
  5. GCD = number2
  6. Print the GCD

Below is the implementation:

# function which computes and returns the highest common factor of the given two numbers
def findGcd(number1, number2):
    while(number2):
        number1, number2 = number2, number1 % number2
    return number1


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation:

We’ll keep looping until y equals zero. In Python, the statement number1, number2 = number2, number1 % number2 swaps values.

In each iteration, the value of number2 is placed in number1 and the remainder (number1 % number2) is placed in number2. We have H.C.F. in number1 when number2 becomes zero.

Method #3:Using gcd() function in math module

This is the simplest and quick method to calculate the greatest common divisor of the given two numbers.

Approach:

  • Import the math module
  • Use math.gcd(number1,number2) to calculate the gcd of the numbers number1 and number2.
  • Print the result.

Below is the implementation:

# importing math module
import math
# function which computes and returns the highest common factor of the given two numbers


def findGcd(number1, number2):
    # calculating gcd using gcd() function
    resGcd = math.gcd(number1, number2)
    # return the gcd of the number 1 and number2
    return resGcd


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation :It just calculated the gcd in 1 line which is math.gcd()
Related Programs:

Python Program to Calculate the HCF/GCD Read More »

Pascal’s Triangle using Python

Python program to print Pascal’s Triangle

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Pascal Triangle Definition:

Pascal’s triangle is a lovely shape produced by arranging numbers. The sum of the two numbers above it is used to produce each number. This triangle’s outside edges are always 1. The triangle is depicted in the diagram below.

Explanation:

To illustrate the triangle in a nutshell, the first line is 1. There are two ones in the line after that. The second line is here.

1 2 1 is the third line, which is created by adding the ones from the previous line. Similarly, the number of 1 and 2 in an alternative pattern forms the fourth line, and so on.

Examples of pascal Triangle

Example 1:

Input :

height =5

Output:

       1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Example 1:

Input :

height =10

Output :

           1
          1 1
         1 2 1
        1 3 3 1
       1 4 6 4 1
      1 5 10 10 5 1
     1 6 15 20 15 6 1
    1 7 21 35 35 21 7 1
   1 8 28 56 70 56 28 8 1
  1 9 36 84 126 126 84 36 9 1

Pascal Triangle in Python

Below are the methods to print the pascal triangle.

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1: Implementation Using zip function

Using the oneval variable, we will first initialise the top row in this function. Variable zerovalue=0 is also set to zero. To run the code for n iterations, we’ll use a for loop.

We’ll print the list generated by the oneval variable within the for loop. We’ll now add the onevalue to left and right elements. We’ve also used the zip feature in this case.

Below is the implementation:

def printPascal(height):
    onevalue = [1]
    zero = [0]
    for i in range(height):
        print(*onevalue)
        onevalue = [left+right for left,
                    right in zip(onevalue+zero, zero+onevalue)]


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Method #2:Using NCR

Approach:

  • Consider the number of rows to be printed; let’s say it’s n.
  • To print the rows, repeat iteration I from 0 to n times.
  • Iterate for j from 0 to (N – 1) in the inner loop.
  • ” “ is a single blank space to be printed.
  • It’s enough to close the inner loop (j loop) for left spacing.
  • Make an inner iteration from 0 to I for j.
  • nCr of I and j should be printed.
  • Close the inner loop.
  • For each inner iteration, print a newline character (\n).

Below is the implementation:

# impoerting factorial fucntion from math module
from math import factorial


def printPascal(height):
    for i in range(height):
        for j in range(height-i+1):

            # for spacing in left
            print(end=" ")

        for j in range(i+1):
            print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")

    # printing in new line
        print()


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

      1 
     1 1 
    1 2 1 
   1 3 3 1 
  1 4 6 4 1

Method #3:Using Binomial Coefficients

The following definition of a Binomial Coefficient may be used to optimise the above code the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines begin with value 1. The idea is to use C to measure C(line, i) using C(line, i-1).

C(line, i) = C(line, i-1) * (line - i + 1) / i

Below is the implementation:

def printPascal(height):
    for i in range(1, height+1):
        for j in range(0, height-i+1):
            print(' ', end='')

        # since first eelement is always 1
        onevalue = 1
        for j in range(1, i+1):

            # first value of every line is 1 always.
            print(' ', onevalue, sep='', end='')

            # using binomial cofficients to calculat using onevalue
            onevalue = onevalue * (i - j) // j
        print()


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

       1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

Related Programs:

Python program to print Pascal’s Triangle Read More »

Program to Find the Factors of a Number in Python and C++ Programming

Python Program to Find the Factors of a Number | C++ Program to Find Factors

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Factors of a number:

When two whole numbers are multiplied, the result is a product. The factors of the product are the numbers we multiply.

In mathematics, a factor is a number or algebraic expression that equally divides another number or expression, leaving no remainder.

The prime number is defined as a number that has only two factors one and itself. Composite numbers are those that contain more than two variables.

Given a number the task is to print the factors of the given number.

Examples:

Example1:

Input:

given_number=360

Output:

printing the factors of given number
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

Example2:

Input:

given_number=10

Output:

printing the factors of given number
1
2
5
10

Program to Find the Factors of a Number

Below are the ways to find the factors of a number:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Using for loop to loop from 1 to N in Python

Algorithm:

Divide a positive number “N” by the natural numbers 1 to “N” to find the factor. If a number is divisible by a natural number, the factor is the natural number. A number N can only have factors in the range of 1 to N.

Approach:

  • Assume the input is a number N.
  • Create an iterator variable and set its value to 1.
  • Using an iterator variable to divide the number N
  • It is a factor of the given number N if it is divisible.
  • The iterator variable should be increased.
  • Rep steps 4 and 5 until the iterator variable reaches the value N.

This is the simplest and most straightforward way to find variables in a Python number programme. While declaring the variables, we’ll take a number. Python software that uses a for-loop to find factors of a number and print the factors on the screen.

Below is the implementation:

# given number
number = 360
# printing the factors of given number
print("printing the factors of given number : ")
# using for loop
for i in range(1, number+1):
    # checking if iterator divides the number if so then print it(because it is factor)
    if(number % i == 0):
        print(i)

Output:

printing the factors of given number : 
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

2)Using for loop to loop from 1 to N in C++

It is similar to method 1 except the syntax. Let us see how to find factors  using for loop in c++

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{ // given number
    int number = 360;
    // printing the factors
    cout << "printing the factors of given number :"
         << endl;
    // using for loop to loop from 1 to N
    for (int i = 1; i <= number; i++)
        // checking if iterator divides the number if so
        // then print it(because it is factor)
        if (number % i == 0)
            cout << i << endl;
    return 0;
}

Output:

printing the factors of given number :
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

We can see that the outputs of both the programs are same

3)Limitations of running loop from 1 to N

In these two methods the loop runs from 1 to number N.

Hence we can say that the time complexity of above methods are O(n).

What if the number is very large?

Like 10^18 the above methods takes nearly 31 years to execute.

Then How to avoid this?

We can see that the factors of the numbers exist from 1 to N/2 except number itself.

But this also takes nearly 15 yrs to execute.

So to above this we loop till square root of N in next method which gives Time Complexity O(Sqrt(n)).

4)Using while loop to loop from 1 to SQRT(N) in Python

Many of the divisors are present in pairs if we look closely. For eg, if n = 16, the divisors are (1,16), (2,8), and (3,8), (4,4)
We could significantly speed up our program if we took advantage of this fact.
However, if there are two equal divisors, as in the case of, we must be cautious (4, 4). In that case, we’d just print one of them.

We use while loop to loop from 1 to sqrt(number)

Below is the implementation:

# importing math module
import math
# given number
number = 360
# taking a iterator and initlaizing it with 1
i = 1
print("printing the factors of given number : ")
# looping till sqrt(number) using while
while i <= math.sqrt(number):

    if (number % i == 0):

        # If both thee divisors are equal then print only one divisor
        if (number / i == i):
            print(i)
        else:
            # else print both the divisors
            print(i)
            print(number//i)
   # increment the iterator by 1
    i += 1

Output:

printing the factors of given number : 
1
360
2
180
3
120
4
90
5
72
6
60
8
45
9
40
10
36
12
30
15
24
18
20

Related Programs:

Python Program to Find the Factors of a Number | C++ Program to Find Factors Read More »

Program to Calculate LCM of Two numbers

Python Program to Find the LCM of Two Numbers

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

We’ll learn how to find the LCM of two numbers in Python programming in this tutorial.

LCM:

What exactly does LCM stand for? The Least Common Multiple of two numbers is referred to as LCM. The LCM of two numbers a and b, for example, is the lowest positive integer divisible by both.

Given two numbers a and b , the task is to write the program which calculates lcm of a and b in Python.

Examples:

Example1:

Input:

a= 23   b=12

Output:

The LCM of the given two numbers 23 , 12 = 276

Example2:

Input:

a= 18 b=72

Output:

The LCM of the given two numbers 18 , 72 = 72

Example3:

Input:

a= 4 b=8

Output:

The LCM of the given two numbers 4 , 8 = 8

Example4:

Input:

a= 9 b=9

Output:

The LCM of the given two numbers 9 , 9 = 9

Explanation:

 The least common divisor of two numbers is number itself if both the numbers are equal

Program to Calculate LCM of Two numbers in Python

There are several ways to calculate the lcm of two numbers in Python some of them are:

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Method #1:Using while loop

Algorithm:

  • Scan or give static input for the numbers a and b.
  • Using an If condition, find the bigger value and assign it to the variable ‘max.’
  • Check whether the remainder of (max %a) and (max %b) equals zero or not using an If condition within the while loop.
  •  Print max, which is the LCM of two numbers, if true.
  • If not, use a break statement to skip that value.
  • End of the execution of the program

Below is the implementation:

# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding bigger number of the given two numbers using if statement
if(number1 > number2):
    maxValue = number1
else:
    maxValue = number2
while(True):
    if(maxValue % number1 == 0 and maxValue % number2 == 0):
        print("The LCM of the given two numbers",
              number1, ",", number2, "=", maxValue)
        break
    maxValue = maxValue + 1

Output:

The LCM of the given two numbers 23 , 12 = 276

Explanation:

  • Both numbers must be entered by the user/static declaration and stored in separate variables.
  • An if statement is used to determine which of the two values is smaller and save the result in a minimum variable.
  • Then, unless break is used, a while loop is employed with a condition that is always true (or 1).
  • Then, within the loop, an if statement is used to determine whether the value in the minimum variable is divisible by both numbers.
  • If it is divisible, the break statement exits the loop.
  • If it is not divisible, the minimum variable’s value is increased.
  • The result(lcm ) will be printed.

Method #2:Using GCD/HCF of the given two numbers

The LCM of two numbers can be determined using the math module’s gcd() function. Consider the following illustration.

Below is the implementation:

# importing math
import math
# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding lcm of the given two values
lcmValue = (number1*number2)//math.gcd(number1, number2)
print("The LCM of the given two numbers",
      number1, ",", number2, "=", lcmValue)

Output:

The LCM of the given two numbers 23 , 12 = 276

Method #3:Using Numpy lcm function.

We can calculate the lcm of the given two numbers using numpy.

We use numpy lcm function to find the lcm of given two numbers.

First We need to import the numpy to use lcm function as below

import numpy as np

we can find lcm using np.lcm(number1,number2) .

Here number1 and number2 are the parameters of the lcm() function.

Below is the implementation:

# importing numpy
import numpy as np
# given two numbers
# given number a
number1 = 23
# given number b
number2 = 12
# finding lcm of the given two numbers number1 and number2
lcmValue = np.lcm(number1, number2)
# printing the lcm of number1 and number2
print("The LCM of the given two numbers",
      number1, ",", number2, "=", lcmValue)

Output:

The LCM of the given two numbers 23 , 12 = 276

Related Programs:

Python Program to Find the LCM of Two Numbers Read More »