Python

Program to Find the Total Number of Bits Needed to be Flipped

Python Program to Find the Total Number of Bits Needed to be Flipped

Given two numbers the task is to print the number of bits to be flipped to convert the given number to the other number.

Examples:

Example1:

Input:

given the first number = 12
given the second number = 9

Output:

Binary representations of the given two numbers are :
12 = 1100
9 = 1001
The total number of bits to be flipped = 2

Example2:

Input:

given the first number = 59
given the second number = 3

Output:

Binary representations of the given two numbers are :
59 = 111011
3 = 11
The total number of bits to be flipped = 3

Program to Find the Total Number of Bits Needed to be Flipped

Below is the full approach to print the number of bits to be flipped to convert the given number to the other number.

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

1)Algorithm

This problem can be rephrased as determining the number of dissimilar corresponding bits in firstnumber and secondnumber. And the bitwise XOR operator () can assist us in determining this. The XOR of two bits returns 1 only if the bits are not the same. As a result, our solution consists of two easy steps:

1. Determine the firstnumber and secondnumber’s bitwise XOR.
2. Determine the number of set bits in the result.

1. Calculate XOR of firstnumber and secondnumber.
firstnumber _xor_secondnumber = firstnumber ^ secondnumber
2. Count the set bits in the above
calculated XOR result.
countSetBits ( firstnumber _xor_secondnumber)

2)Using XOR Operator and Count Variable(Static Input)

Approach:

  • Give the two numbers as static input and store them in two separate variables.
  • Pass the given two numbers as arguments to the countFlipbits function which calculates the total number of bits to be flipped to convert one number into another.
  • Calculate the xor value of the two numbers and store it in a result say resultnum.
  • Use the while loop to calculate the total number of set bits in the resultnum.
  • Return the number of set bits which is the result (number of bits to be flipped).
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the two numbers as arguments
# and return the number of bits to be flipped


def countFlipbits(firstnumber, secondnumber):
    # Calculate the xor value of the two numbers and store it in a result say resultnum.
    resultnum = firstnumber ^ secondnumber
    # Use the while loop to calculate the total number of set bits in the resultnum.
    setbitCounter = 0
    while resultnum:
        resultnum = resultnum & (resultnum - 1)
        setbitCounter = setbitCounter + 1
    # Return the number of set bits which is the result (number of bits to be flipped).
    return setbitCounter


# Driver Code
# Give the two numbers as static input and store them in two separate variables.
firstnumber = 12
secondnumber = 9
# Pass the given two numbers as arguments to the ( function which calculates the total number
# of bits to be flipped to convert one number into another.
print('Binary representations of the given two numbers are :')
print(firstnumber, '=', bin(firstnumber)[2:])
print(secondnumber, '=', bin(secondnumber)[2:])
print('The total number of bits to be flipped =',
      countFlipbits(firstnumber, secondnumber))

Output:

Binary representations of the given two numbers are :
12 = 1100
9 = 1001
The total number of bits to be flipped = 2

3)Using XOR Operator and Count Variable(User Input separated by spaces)

Approach:

  • Give the two numbers as user input using int, map(), and split() functions.
  • Store them in two separate variables.
  • Pass the given two numbers as arguments to the countFlipbits function which calculates the total number of bits to be flipped to convert one number into another.
  • Calculate the xor value of the two numbers and store it in a result say resultnum.
  • Use the while loop to calculate the total number of set bits in the resultnum.
  • Return the number of set bits which is the result (number of bits to be flipped).
  • Print the result.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the two numbers as arguments
# and return the number of bits to be flipped


def countFlipbits(firstnumber, secondnumber):
    # Calculate the xor value of the two numbers and store it in a result say resultnum.
    resultnum = firstnumber ^ secondnumber
    # Use the while loop to calculate the total number of set bits in the resultnum.
    setbitCounter = 0
    while resultnum:
        resultnum = resultnum & (resultnum - 1)
        setbitCounter = setbitCounter + 1
    # Return the number of set bits which is the result (number of bits to be flipped).
    return setbitCounter


# Driver Code
# Give the two numbers as user input using int, map(), and split() functions.
# Store them in two separate variables.
firstnumber, secondnumber = map(int, input(
    'Enter some random two numbers separated by spaces = ').split())
# Pass the given two numbers as arguments to the ( function which calculates the total number
# of bits to be flipped to convert one number into another.
print('Binary representations of the given two numbers are :')
print(firstnumber, '=', bin(firstnumber)[2:])
print(secondnumber, '=', bin(secondnumber)[2:])
print('The total number of bits to be flipped =',
      countFlipbits(firstnumber, secondnumber))

Output:

Enter some random two numbers separated by spaces = 54 96
Binary representations of the given two numbers are :
54 = 110110
96 = 1100000
The total number of bits to be flipped = 4

4)Using XOR Operator and Built-in Count function(Static Input)

Approach:

  • Give the two numbers as static input and store them in two separate variables.
  • Pass the given two numbers as arguments to the countFlipbits function which calculates the total number of bits to be flipped to convert one number into another.
  • Calculate the xor value of the two numbers and store it in a result say resultnum.
  • Convert this resultnum to binary and calculate the total number of sets bits in it using the count() function.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the two numbers as arguments
# and return the number of bits to be flipped


def countFlipbits(firstnumber, secondnumber):
    # Calculate the xor value of the two numbers and store it in a result say resultnum.
    resultnum = firstnumber ^ secondnumber
    # Convert this resultnum to binary and calculate the total
    # number of sets bits in it using the count() function.
    binNumber = bin(resultnum)
    setbitCounter = binNumber.count('1')
    return setbitCounter


# Driver Code

# Driver Code
# Give the two numbers as static input and store them in two separate variables.
firstnumber = 18
secondnumber = 68
# Pass the given two numbers as arguments to the ( function which calculates the total number
# of bits to be flipped to convert one number into another.
print('Binary representations of the given two numbers are :')
print(firstnumber, '=', bin(firstnumber)[2:])
print(secondnumber, '=', bin(secondnumber)[2:])
print('The total number of bits to be flipped =',
      countFlipbits(firstnumber, secondnumber))

Output:

Binary representations of the given two numbers are :
18 = 10010
68 = 1000100
The total number of bits to be flipped = 4

5)Using XOR Operator and Built-in Count function(User Input Separated by Newline)

Approach:

  • Give the first number as user input using int(input()) and store it in a variable.
  • Give the second number as user input using int(input()) and store it in another variable.
  • Pass the given two numbers as arguments to the countFlipbits function which calculates the total number of bits to be flipped to convert one number into another.
  • Calculate the xor value of the two numbers and store it in a result say resultnum.
  • Convert this resultnum to binary and calculate the total number of sets bits in it using the count() function.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the two numbers as arguments
# and return the number of bits to be flipped


def countFlipbits(firstnumber, secondnumber):
    # Calculate the xor value of the two numbers and store it in a result say resultnum.
    resultnum = firstnumber ^ secondnumber
    # Convert this resultnum to binary and calculate the total
    # number of sets bits in it using the count() function.
    binNumber = bin(resultnum)
    setbitCounter = binNumber.count('1')
    return setbitCounter


# Driver Code

# Driver Code
# Give the first number as user input using int(input()) and store it in a variable.
firstnumber = int(input('Enter first random number = '))
# Give the second number as user input using int(input()) and store it in another variable.
secondnumber = int(input('Enter second random number = '))
# Pass the given two numbers as arguments to the ( function which calculates the total number
# of bits to be flipped to convert one number into another.
print('Binary representations of the given two numbers are :')
print(firstnumber, '=', bin(firstnumber)[2:])
print(secondnumber, '=', bin(secondnumber)[2:])
print('The total number of bits to be flipped =',
      countFlipbits(firstnumber, secondnumber))

Output:

Enter first random number = 59
Enter second random number = 3
Binary representations of the given two numbers are :
59 = 111011
3 = 11
The total number of bits to be flipped = 3

Related Programs:

Python Program to Find the Total Number of Bits Needed to be Flipped Read More »

Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes

Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes

The Sieve of Eratosthenes is a very old and conventional algorithm for finding all prime numbers that are less or equal to a given number. If the number is less than or equal to 10 million or so, the Eratosthenes sieve is highly effective. You may get a thorough explanation of the algorithm on Wikipedia.

Given the lower limit and upper limit the task is to print prime numbers in the given range using sieve of Eratosthenes in Python.

Examples:

Example1:

Input:

Enter some random upper limit range = 529

Output:

The prime numbers from 1 to 529 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 
149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443
449 457 461 463 467 479 487 491 499 503 509 521 523

Example2:

Input:

Enter some random upper limit range = 129

Output:

The prime numbers from 1 to 129 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127

Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

1)Algorithm

  • Make a Boolean array of size n, and consider it an array that shows whether the i th entry is Prime or not.
  • First, make them all primes by assigning a True value to each element of the array.
  • Now, because we know the smallest prime number is 2, set the value of variable p to 2.
  • Begin by looking for all multiples of p and marking them as False.
  • Iterate until the value of p equals n, then mark all multiples as False.
  • Finally, the array members having the value True are the requisite primes.
  • For optimization purposes, the value of square of p is checked rather than p during the iteration.

2)Implementation (Static Input)

Approach:

  • Give the value of the upper limit n as static input.
  • Fill the sieve with numbers ranging from 2 to n.
  • Use a while loop that checks to see if the sieve is empty.
  • Find the smallest prime number.
  • Take that number away, then it’s multiples
  • Continue until the sieve is completely empty.
  • Exit of program.

Below is the implementation:

# Give the value of the upper limit n as static input.
numb = 20
print('The prime numbers from 1 to', numb, 'are :')
# Fill the sieve with numbers ranging from 2 to n.
sievearray = set(range(2, numb+1))
# Use a while loop that checks to see if the sieve is empty.
while sievearray:
  # Find the smallest prime number.
    primenum = min(sievearray)
    # printing the primenum
    print(primenum, end=" ")
    sievearray -= set(range(primenum, numb+1, primenum))

Output:

The prime numbers from 1 to 20 are :
2 3 5 7 11 13 17 19

Explanation:

  • Give the value of the upper limit n as static input.
  • The sieve is initialized with a set ranging from 2 to n (n+1 is not included)
  • The while loop ensures that the sieve is not empty.
  • The variable prime is initialized with the sieve’s smallest number, and the prime number is reported.
  • The sieve is then emptied of all prime number multiples.
  • Steps 4 and 5 are repeated until the sieve’s value is empty.

3)Implementation (User Input)

Approach:

  • Give the value of the upper limit n as user input using the int(input()) function.
  • Fill the sieve with numbers ranging from 2 to n.
  • Use a while loop that checks to see if the sieve is empty.
  • Find the smallest prime number.
  • Take that number away, then it’s multiples
  • Continue until the sieve is completely empty.
  • The Exit of the program.

Below is the implementation:

# Give the value of the upper limit n as user input using int(input()) function.
numb = int(input('Enter some random upper limit range = '))
print('The prime numbers from 1 to', numb, 'are :')
# Fill the sieve with numbers ranging from 2 to n.
sievearray = set(range(2, numb+1))
# Use a while loop that checks to see if the sieve is empty.
while sievearray:
  # Find the smallest prime number.
    primenum = min(sievearray)
    # printing the primenum
    print(primenum, end=" ")
    sievearray -= set(range(primenum, numb+1, primenum))

Output:

Enter some random upper limit range = 529
The prime numbers from 1 to 529 are :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 
149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281
 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443
 449 457 461 463 467 479 487 491 499 503 509 521 523

This algorithm generates all primes with values less than n. It features a common improvement in that it begins enumerating the multiples of each prime I from i^2. This approach has a time complexity of O(n log log n), assuming that the array update is an O(1) operation, which is frequently the case.
Related Programs:

Python Program to Read Print Prime Numbers in a Range using Sieve of Eratosthenes Read More »

Program to Swap all Odd and Even Bits of a Number

Python Program to Swap all Odd and Even Bits of a Number

Given a number, the task is to swap all odd and even bits of the given number in Python.

In binary, the number 185 is represented as 10111001. The bits in bold are in even positions, and they are 1 1 1 0, while the bits in odd positions are 0 1 0 1.

After swapping the odd and even bits, we get 118(1110110)

Examples:

Example1:

Input:

Given Number =456

Output:

The original given number is = 456
The modified number after swapping bits is = 708

Example2:

Input:

Given Number =185

Output:

The original given number is = 185
The modified number after swapping bits is = 118

Program to Swap all Odd and Even Bits of a Number in Python

Below are the ways to swap all odd and even bits of the given number in Python.

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Method #1: Using Binary Operators (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • To extract the odd bits from the number, use a bitwise AND operation with hexadecimal 55555555.
  • To extract the even bits from the number, use a bitwise AND operation with hexadecimal AAAAAAAA.
  • Perform a left shift << by 1 position to move odd bits to even positions.
  • Perform a right shift >> by 1 place to move even bits to odd positions.
  • Finally, using the bitwise OR operator, to combine both bits.
  • Print the modified Number after swapping odd and even bits of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 185
# To extract the odd bits from the number,
# use a bitwise AND operation with hexadecimal 55555555.
oddbitsnumb = numb & 0x55555555
# To extract the even bits from the number,
# use a bitwise AND operation with hexadecimal AAAAAAAA.
evenbitsnumb = numb & 0xAAAAAAAA
# Perform a left shift << by 1 position to move odd bits to even positions.
oddbitsnumb = oddbitsnumb << 1
# Perform a right shift >> by 1 place to move even bits to odd positions.
evenbitsnumb = evenbitsnumb >> 1
# Finally, using the bitwise OR operator, to combine both bits.
modifdnumb = oddbitsnumb | evenbitsnumb
# Print the modified Number after swapping odd and even bits of the given number.
print('The original given number is =', numb)
print('The modified number after swapping bits is =', modifdnumb)

Output:

The original given number is = 185
The modified number after swapping bits is = 118

Method #2: Using Binary Operators (User Input)

Approach:

  • Give the number as user input using int(input()) and store it in a variable.
  • To extract the odd bits from the number, use a bitwise AND operation with hexadecimal 55555555.
  • To extract the even bits from the number, use a bitwise AND operation with hexadecimal AAAAAAAA.
  • Perform a left shift << by 1 position to move odd bits to even positions.
  • Perform a right shift >> by 1 place to move even bits to odd positions.
  • Finally, using the bitwise OR operator, to combine both bits.
  • Print the modified Number after swapping odd and even bits of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using int(input()) and store it in another variable.
numb = int(input('Enter some random number = '))
# To extract the odd bits from the number,
# use a bitwise AND operation with hexadecimal 55555555.
oddbitsnumb = numb & 0x55555555
# To extract the even bits from the number,
# use a bitwise AND operation with hexadecimal AAAAAAAA.
evenbitsnumb = numb & 0xAAAAAAAA
# Perform a left shift << by 1 position to move odd bits to even positions.
oddbitsnumb = oddbitsnumb << 1
# Perform a right shift >> by 1 place to move even bits to odd positions.
evenbitsnumb = evenbitsnumb >> 1
# Finally, using the bitwise OR operator, to combine both bits.
modifdnumb = oddbitsnumb | evenbitsnumb
# Print the modified Number after swapping odd and even bits of the given number.
print('The original given number is =', numb)
print('The modified number after swapping bits is =', modifdnumb)

Output:

Enter some random number = 456
The original given number is = 456
The modified number after swapping bits is = 708

Related Programs:

Python Program to Swap all Odd and Even Bits of a Number Read More »

Program to Flipping the Binary Bits

Python Program to Flipping the Binary Bits

Given a binary string, the task is to flip the bits in the given binary string in Python.

Examples:

Example1:

Input:

Given Binary string =1101010001001

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Example2:

Input:

Given Binary string =00110011111

Output:

The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Program to Flipping the Binary Bits in Python

Below are the ways to flip the bits in the given binary string in Python.

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Take an empty string(say flipbinary) which is the result after flipping the bits and initialize its value to a null string using “”.
  • Traverse the given binary string using For loop.
  • If the bit is 1 then concatenate the flipbinary with 0.
  • Else concatenate the flipbinary with 1.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')
# Take an empty string(say flipbinary) which is the result after flipping the bits
# and initialize its value to a null string using "".
flipbinary = ""
# Traverse the given binary string using For loop.
for bitval in gvnbinstring:
    # If the bit is 1 then concatenate the flipbinary with 0.
    if bitval == '1':
        flipbinary += '0'
    # Else concatenate the flipbinary with 1.
    else:
        flipbinary += '1'
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 0011100110101010
The given binary string before flipping bits is [ 0011100110101010 ]
The given binary string after flipping bits is [ 1100011001010101 ]

Method #3: Using replace() function (Static Input)

Approach:

  • Give the binary string as static input and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as static input and store it in a variable.
gvnbinstring = '1101010001001'

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

The given binary string before flipping bits is [ 1101010001001 ]
The given binary string after flipping bits is [ 0010101110110 ]

Method #4: Using replace() function (User Input)

Approach:

  • Give the binary string as user input using input() and store it in a variable.
  • Replace all 1’s present in the given binary string with some random character like p.
  • Replace all 0’s present in the given binary string with 1.
  • Replace all p’s present in the given binary string with 0.
  • Here ‘p’ acts as a temporary variable.
  • Print the modified binary string after flipping the bits.
  • The Exit of the Program.

Below is the implementation:

# Give the binary string as user input using input() and store it in a variable.
gvnbinstring = input('Enter some random binary string = ')

# Replace all 1's present in the given binary string
# with some random character like p.
flipbinary = gvnbinstring.replace('1', 'p')
# Replace all 0's present in the given
# binary string with 1.
flipbinary = flipbinary.replace('0', '1')
# Replace all p's present in the given
# binary string with 0.
# Here 'p' acts as a temporary variable.
flipbinary = flipbinary.replace('p', '0')
# Print the modified binary string after flipping the bits.
print('The given binary string before flipping bits is [', gvnbinstring, ']')
print('The given binary string after flipping bits is [', flipbinary, ']')

Output:

Enter some random binary string = 00110011111
The given binary string before flipping bits is [ 00110011111 ]
The given binary string after flipping bits is [ 11001100000 ]

Related Programs:

Python Program to Flipping the Binary Bits Read More »

Program to Print Neon numbers in a Range

Python Program to Print Neon numbers in a Range

In this article, we will learn how to print Neon numbers within a specific range in Python. You will learn what a Neon number is, how to check whether a given number is a Neon number, and how to write a Python code that outputs all the Neon numbers within the user-specified range.

Neon Number:

A Neon Number is a number whose square sum of digits equals the original number.

Ex: 9

Square of 9 =81

Sum of digits of square = 8 +1 =9 ,So it is Neon Number

Examples:

Example1:

Input:

Given upper limit range =1
Given lower limit range =7

Output:

The Neon numbers in the given range 1 and 7 are:
1

Example2:

Input:

Given upper limit range =1
Given lower limit range =23

Output:

Enter lower limit range and upper limit range separate bt spaces = 1 23
The Neon numbers in the given range 1 and 23 are:
1 9

Program to Print Neon numbers in a Range in Python

Below are the ways to print all the Neon numbers in the given range.

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Method #1: Using list() and sum() functions (Static Input)

Approach:

  • Create a function checkNeonnumb() which accepts the number as an argument and returns true if it is Neon number else returns False.
  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Inside the checkNeonnumb() function
  • Calculate the square of the given number/argument using the ** operator or multiply the given number by itself and store it in a variable.
  • Convert this squared number into a list of digits using list(),int(),map(),str() functions.
  • Store this list in a variable.
  • Calculate the sum of digits of this list using the sum() function.
  • Check if this sum is equal to the given number or not using the If conditional statement.
  • If it is true then the given number is a Neon Number so return True
  • Else the given number is not a Neon Number so return False.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop pass the iterator value to checkNeonnumb() function.
  • If it returns true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkNeonNumb() which accepts the number as an argument and
# returns true if it is Neon number else returns False.


def checkNeonNumb(numb):
    # Calculate the square of the given number/argument using the ** operator or multiply
    # the given number by itself and store it in a variable.
    squarnumb = numb**2
    # Convert this squared number into a list of digits
    # using list(),int(),map(),str() functions.
    # Store this list in a variable.
    numbedigit = list(map(int, str(squarnumb)))
    # Calculate the sum of digits of this list using the sum() function.
    sumdigi = sum(numbedigit)
    # Check if this sum is equal to the given number
    # or not using the If conditional statement.
    # If it is true then the given number is a Neon Number so return True
    if(sumdigi == numb):
        return True
    # Else the given number is not a Neon Number so return False.
    else:
        return False


# Give the lower limit range as static input and store it in a variable.
lowlimrange = 1
# Give the upper limit range as static input and store it in another variable.
upplimrange = 7
print('The Neon numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for p in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkNeonNumb(p)):
        # If it returns true then print the iterator value.
        print(p, end=' ')

Output:

The Neon numbers in the given range 1 and 7 are:
1

Method #2: Using list() and sum() functions (User Input)

Approach:

  • Create a function checkNeonnumb() which accepts the number as an argument and returns true if it is Neon number else returns False.
  • Give the lower limit range and upper limit range as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Inside the checkNeonnumb() function
  • Calculate the square of the given number/argument using the ** operator or multiply the given number by itself and store it in a variable.
  • Convert this squared number into a list of digits using list(),int(),map(),str() functions.
  • Store this list in a variable.
  • Calculate the sum of digits of this list using the sum() function.
  • Check if this sum is equal to the given number or not using the If conditional statement.
  • If it is true then the given number is a Neon Number so return True
  • Else the given number is not a Neon Number so return False.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop pass the iterator value to checkNeonnumb() function.
  • If it returns true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkNeonNumb() which accepts the number as an argument and
# returns true if it is Neon number else returns False.


def checkNeonNumb(numb):
    # Calculate the square of the given number/argument using the ** operator or multiply
    # the given number by itself and store it in a variable.
    squarnumb = numb**2
    # Convert this squared number into a list of digits
    # using list(),int(),map(),str() functions.
    # Store this list in a variable.
    numbedigit = list(map(int, str(squarnumb)))
    # Calculate the sum of digits of this list using the sum() function.
    sumdigi = sum(numbedigit)
    # Check if this sum is equal to the given number
    # or not using the If conditional statement.
    # If it is true then the given number is a Neon Number so return True
    if(sumdigi == numb):
        return True
    # Else the given number is not a Neon Number so return False.
    else:
        return False


# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate bt spaces = ').split())
print('The Neon numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for p in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkNeonNumb(p)):
        # If it returns true then print the iterator value.
        print(p, end=' ')

Output:

Enter lower limit range and upper limit range separate bt spaces = 1 23
The Neon numbers in the given range 1 and 23 are:
1 9

Related Programs:

Python Program to Print Neon numbers in a Range Read More »

Program to Print all Happy Numbers within a given Range

Python Program to Print all Happy Numbers within a given Range

In this article, we will learn how to print happy numbers within a specific range in Python. You will learn what a happy number is, how to check whether a given number is a happy number, and how to write Python code that outputs all the happy numbers within the user-specified range.

Happy Number :

If the repeating sum of the digits squared equals one, the number is said to be a Happy Number. If we continue this method and get outcome 1, we have a happy number. If the outcome is 4, it enters an infinite loop and is not a happy number. Let’s look at an example to help you grasp it better.

Given Number = 320
Square of the digits  = 32 + 22 + 02 = 13
Square of the digits  = 12 + 32 = 10
Square of the digits  = 12 + 02 = 1

Other Examples of happy numbers  =7, 28, 100 etc.

Examples:

Example1:

Input:

Given upper limit range =19
Given lower limit range =145

Output:

The happy numbers in the given range 19 and 145 are:
19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 103 109 129 130 133 139

Example2:

Input:

Given upper limit range =333
Given lower limit range =444

Output:

The happy numbers in the given range 333 and 444 are:
338 356 362 365 367 368 376 379 383 386 391 392 397 404 409 440

Program to Print all Happy numbers within a given range in Python

Below are the ways to print all the happy numbers in the given range.

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Method #1: Using For Loop (Static Input)

Approach:

  • Create a function checkhapppynumb() which accepts the number as an argument and returns true if it is happy number else returns False.
  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Create a function digitSquareSum() that accepts the given number as an argument and returns the sum of squares of digits.
  • Inside the digitSquareSum() function.
  • Convert the given argument to string using the str() function.
  • Convert the given argument into list of digits using list(),map(),int() functions.
  • Store it in a variable.
  • Take a variable sumsquaredigits and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Increment the value of sumsquaredigits by the square of the digit(iterator value).
  • Return the sumsquaredigits value.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop pass the iterator value to checkhapppynumb() function.
  • Inside the checkhapppynumb() function.
  • Take a variable reslt and initialize its value to the given argument.
  • Loop till the reslt is not equal to 1 or 4 using while loop.
  • Inside the loop pass the reslt value to digitSquareSum() and store it in the same variable reslt.
  • After the end of the while loop, Check whether reslt value is 1 or not using the If statement.
  • If it is true then the given number is a happy number so return True
  • Else it is not a happy number so return False.
  • If it returns true then print the iterator value with space.
  • The Exit of the Program.

Below is the implementation:

# Create a function digitSquareSum() that accepts the given number
# as an argument and returns the sum of squares of digits.


def digitSquareSum(resltnumber):
    # Inside the digitSquareSum() function.
    # Convert the given argument to string using the str() function.
    strnumbe = str(resltnumber)
    # Convert the given argument into list of digits using list(),map(),int() functions.
    # Store it in a variable.
    numbrlistdigits = list(map(int, strnumbe))
    # Take a variable sumsquaredigits and initialize its value to 0.
    sumsquaredigits = 0
    # Loop in this digits list using For loop.
    for digitvalu in numbrlistdigits:
        # Increment the value of sumsquaredigits by the square
        # of the digit(iterator value).
        sumsquaredigits = sumsquaredigits+(digitvalu**2)
    # Return the sumsquaredigits value
    return sumsquaredigits

# Create a function checkhapppynumb() which accepts the number as an argument
# and returns true if it is happy number else returns False.


def checkhapppynumb(numb):
    # Take a variable rest and initialize its value to the given argument.
    rest = numb
    # Loop till the rest is not equal to 1 or 4 using while loop.
    while(rest != 1 and rest != 4):
        # Inside the loop pass the reslt value to digitSquareSum()
        # and store it in the same variable reslt.
        rest = digitSquareSum(rest)
    # After the end of the while loop,
    # Check whether rest value is 1 or not using the If statement.
    if(rest == 1):
        # If it is true then the given number is a happy number so return True
        return True
    else:
        # Else it is not a happy number so return False.
        return False


# Give the lower limit range as static input and store it in a variable.
lowlimrange = 19
# Give the upper limit range as static input and store it in another variable.
upplimrange = 145
print('The happy numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for l in range(lowlimrange, upplimrange+1):
        # IInside the for loop pass the iterator value to checkhapppynumb() function.
    if(checkhapppynumb(l)):
        # If it returns true then print the iterator value.
        print(l, end=' ')

Output:

The happy numbers in the given range 19 and 145 are:
19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 103 109 129 130 133 139

Method #2: Using For Loop (User Input)

Approach:

  • Create a function checkhapppynumb() which accepts the number as an argument and returns true if it is happy number else returns False.
  • Give the lower limit range and upper limit range as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Create a function digitSquareSum() that accepts the given number as an argument and returns the sum of squares of digits.
  • Inside the digitSquareSum() function.
  • Convert the given argument to string using the str() function.
  • Convert the given argument into list of digits using list(),map(),int() functions.
  • Store it in a variable.
  • Take a variable sumsquaredigits and initialize its value to 0.
  • Loop in this digits list using For loop.
  • Increment the value of sumsquaredigits by the square of the digit(iterator value).
  • Return the sumsquaredigits value.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop pass the iterator value to checkhapppynumb() function.
  • Inside the checkhapppynumb() function.
  • Take a variable reslt and initialize its value to the given argument.
  • Loop till the reslt is not equal to 1 or 4 using while loop.
  • Inside the loop pass the reslt value to digitSquareSum() and store it in the same variable reslt.
  • After the end of the while loop, Check whether reslt value is 1 or not using the If statement.
  • If it is true then the given number is a happy number so return True
  • Else it is not a happy number so return False.
  • If it returns true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Create a function digitSquareSum() that accepts the given number
# as an argument and returns the sum of squares of digits.


def digitSquareSum(resltnumber):
    # Inside the digitSquareSum() function.
    # Convert the given argument to string using the str() function.
    strnumbe = str(resltnumber)
    # Convert the given argument into list of digits using list(),map(),int() functions.
    # Store it in a variable.
    numbrlistdigits = list(map(int, strnumbe))
    # Take a variable sumsquaredigits and initialize its value to 0.
    sumsquaredigits = 0
    # Loop in this digits list using For loop.
    for digitvalu in numbrlistdigits:
        # Increment the value of sumsquaredigits by the square
        # of the digit(iterator value).
        sumsquaredigits = sumsquaredigits+(digitvalu**2)
    # Return the sumsquaredigits value
    return sumsquaredigits

# Create a function checkhapppynumb() which accepts the number as an argument
# and returns true if it is happy number else returns False.


def checkhapppynumb(numb):
    # Take a variable rest and initialize its value to the given argument.
    rest = numb
    # Loop till the rest is not equal to 1 or 4 using while loop.
    while(rest != 1 and rest != 4):
        # Inside the loop pass the reslt value to digitSquareSum()
        # and store it in the same variable reslt.
        rest = digitSquareSum(rest)
    # After the end of the while loop,
    # Check whether rest value is 1 or not using the If statement.
    if(rest == 1):
        # If it is true then the given number is a happy number so return True
        return True
    else:
        # Else it is not a happy number so return False.
        return False


# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate bt spaces = ').split())
print('The Harshad numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
print('The happy numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for l in range(lowlimrange, upplimrange+1):
        # IInside the for loop pass the iterator value to checkhapppynumb() function.
    if(checkhapppynumb(l)):
        # If it returns true then print the iterator value.
        print(l, end=' ')

Output:

Enter lower limit range and upper limit range separate bt spaces = 333 444
The Harshad numbers in the given range 333 and 444 are:
The happy numbers in the given range 333 and 444 are:
338 356 362 365 367 368 376 379 383 386 391 392 397 404 409 440

Related Programs:

Python Program to Print all Happy Numbers within a given Range Read More »

Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10

Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10

Lists in Python:

A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given lower limit and upper limit , the task is to print all numbers in the given range which are perfect squares and sum of all Digits in the Number is Less than 10.

Examples:

Example1:

Input:

Enter some random lower limit =5
Enter some random lower limit =525

Output:

Printing the perfect squares numbers list which are less than 10: [9, 16, 25, 36, 81, 100, 121, 144, 225, 324, 400, 441]

Example2:

Input:

Enter some random lower limit =69
Enter some random lower limit =2379

Output:

Printing the perfect squares numbers list which are less than 10: [81, 100, 121, 144, 225, 324, 400, 441, 900, 1024, 1521, 1600, 2025, 2304]

Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10 in Python

There are several ways to find all all numbers in the given range which are perfect squares and sum of all Digits in the Number is Less than 10 and store them in the list some of them are:

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

Method #1:Using List Comprehension (Static Input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • When the element is a perfect square within the range and the total of the digits of the number is less than 10, a list must be generated using list comprehension.
  • After that, the list must be printed.
  • Exit of program

Below is the implementation:

# given lower limit range as static input
lowerlimit = 5
# given upper limit range as static input
upperlimit = 525
# When the element is a perfect square within the range and the total of the digits of the number
# is less than 10, a list must be generated using list comprehension.
prftSquaresList = [k for k in range(
    lowerlimit, upperlimit+1) if (int(k**0.5))**2 == k and sum(list(map(int, str(k)))) < 10]
# printing the list
print("Printing the perfect squares numbers list which are less than 10: ", prftSquaresList)

Output:

Printing the perfect squares numbers list which are less than 10:  [9, 16, 25, 36, 81, 100, 121, 144, 225, 324, 400, 441]

Method #2:Using List Comprehension (User Input)

Approach:

  • Scan the lower limit range and upper limit range as user input using int(input()) which converts string to integer.
  • When the element is a perfect square within the range and the total of the digits of the number is less than 10, a list must be generated using list comprehension.
  • After that, the list must be printed.
  • Exit of program.

Below is the implementation:

# Scan lower limit range as user input
lowerlimit = int(input("Enter some random lower limit ="))
# Scan upper limit range as user  input
upperlimit = int(input("Enter some random lower limit ="))
# When the element is a perfect square within the range and the total of the digits of the number
# is less than 10, a list must be generated using list comprehension.
prftSquaresList = [k for k in range(
    lowerlimit, upperlimit+1) if (int(k**0.5))**2 == k and sum(list(map(int, str(k)))) < 10]
# printing the list
print("Printing the perfect squares numbers list which are less than 10: ", prftSquaresList)

Output:

Enter some random lower limit =69
Enter some random lower limit =2379
Printing the perfect squares numbers list which are less than 10: [81, 100, 121, 144, 225, 324, 400, 441, 900, 1024,
 1521, 1600, 2025, 2304]

Explanation:

  • The upper and lower ranges for the numbers must be entered by the user.
  • To make a list of numbers that are perfect squares and have a sum of digits fewer than ten, list comprehension must be utilized.
  • The second stage of the list comprehension process involves mapping individual digits of a number into a list and calculating the sum of the list’s elements.
  • The list that has been generated is printed.

Method #3:Using for loop (Static Input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Take a empty list say prftSquaresList 
  • Use a for loop that goes from the lower limit range to the upper range using range() function.
  • When the element is a perfect square within the range and the total of the digits of the number is less than 10 then append that element to the prftSquaresList  using append() function.
  • After that, the list must be printed.
  • Exit of program

Below is the implementation:

# given lower limit
# range as static input
lowerlimit = 5
# given upper limit range as static input
upperlimit = 525
# Take a empty list say prftSquaresList 
prftSquaresList = []
# Use a for loop that goes from the lower limit range to the upper range using
# range() function.
for numb in range(lowerlimit, upperlimit+1):
    # When the element is a perfect square within the range and the total of the digits of the number is less than 10
    # then append that element to the prftSquaresList  using append() function.
    if((int(numb**0.5))**2 == numb and sum(list(map(int, str(numb)))) < 10):
        prftSquaresList.append(numb)


# printing the list
print("Printing the perfect squares numbers list which are less than 10: ", prftSquaresList)

Output:

Printing the perfect squares numbers list which are less than 10:  [9, 16, 25, 36, 81, 100, 121, 144, 225, 324, 400,
 441]

Method #4:Using for loop (User Input)

Approach:

  • Scan the lower limit range and upper limit range as user input using int(input()) which converts string to integer.
  • Take a empty list say prftSquaresList 
  • Use a for loop that goes from the lower limit range to the upper range using range() function.
  • When the element is a perfect square within the range and the total of the digits of the number is less than 10 then append that element to the prftSquaresList  using append() function.
  • After that, the list must be printed.
  • Exit of program

Below is the implementation:

# Scan lower limit range as user input
lowerlimit = int(input("Enter some random lower limit ="))
# Scan upper limit range as user  input
upperlimit = int(input("Enter some random lower limit ="))
# Take a empty list say prftSquaresList 
prftSquaresList = []
# Use a for loop that goes from the lower limit range to the upper range using
# range() function.
for numb in range(lowerlimit, upperlimit+1):
    # When the element is a perfect square within the range and the total of the digits of the number is less than 10
    # then append that element to the prftSquaresList  using append() function.
    if((int(numb**0.5))**2 == numb and sum(list(map(int, str(numb)))) < 10):
        prftSquaresList.append(numb)


# printing the list
print("Printing the perfect squares numbers list which are less than 10: ", prftSquaresList)

Output:

Enter some random lower limit =127
Enter some random lower limit =2379
Printing the perfect squares numbers list which are less than 10: [144, 225, 324, 400, 441, 900, 1024, 1521, 1600, 2025, 2304]

Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10 Read More »

Program to Print all the Prime Numbers within a Given Range

Python Program to Print all the Prime Numbers within a Given Range

Given the upper limit range, the task is to print all the prime numbers in the given range in Python.

Examples:

Example1:

Input:

given number = 95

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

Example2:

Input:

given number = 52

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Python Program to Print all the Prime Numbers within a Given Range

There are several ways to print all the prime numbers from 2 to the upper limit range some of them are:

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
givenNumbr = 95
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

The prime numbers from 2 to upper limit [ 95 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89

All the prime numbers till the upper limit range are printed.

Method #2:Using for loop(User Input)

Approach:

  • Give the number as user input with the help of the int(input()) function and store it in a variable.
  • Set the first for loop to have a range of 2 to the upper limit range.
  • Take a temporary variable which is the count variable and initialize it to zero.
  • Allow the second for loop to have a range of 2 to half the number (excluding 1 and the number itself).
  • Then, using the if statement, determine the number of divisors and increment the count variable each time.
  • The number is prime if the number of divisors is lower than or equal to zero.
  • Prime numbers till the given upper limit range are printed.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input with the help
# of the int(input()) function and store it in a variable.
givenNumbr = int(input('Enter some random upper limit range = '))
print('The prime numbers from 2 to upper limit [', givenNumbr, '] :')
# Set the first for loop to have a range of 2 to the upper limit range.
for valu in range(2, givenNumbr+1):
  # Take a temporary variable which is the count variable and initialize it to zero.
    cntvar = 0
    # Allow the second for loop to have a range of 2 to
    # half the number (excluding 1 and the number itself).
    for divi in range(2, valu//2+1):
      # Then, using the if statement, determine the number of divisors
      # and increment the count variable each time.
        if(valu % divi == 0):
            cntvar = cntvar+1
    # The number is prime if the number of divisors is lower than or equal to zero.
    if(cntvar <= 0):
        print(valu, end=' ')

Output:

Enter some random upper limit range = 52
The prime numbers from 2 to upper limit [ 52 ] :
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Explanation:

  • The user must enter the range’s upper limit and save it in a separate variable.
  • The first for loop runs until the user enters an upper limit.
  • The count variable is initially set to 0.
  • Because the for loop runs from 2 to half of the number, 1 and the number itself is not considered divisors.
  • If the remainder is equal to zero, the if statement looks for the number’s divisors.
  • The count variable counts the number of divisors, and if the count is less than or equal to zero, the integer is prime.
  • If the count exceeds zero, the integer is not prime.
  • All the prime numbers till the upper limit range are printed.

Related Programs:

Python Program to Print all the Prime Numbers within a Given Range Read More »

Program to Print Odd Numbers Within a Given Range

Python Program to Print Odd Numbers Within a Given Range

Given lower limit and upper limit, the task is to print all the odd numbers in the given range in Python.

Examples:

Example1:

Input:

given lower limit range = 25
given upper limit range = 79

Output:

25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79

Example2:

Input:

given lower limit range = 23
given upper limit range = 143

Output:

Odd numbers from 23 to 143 are :
23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95
97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143

Program to Print Odd Numbers Within a Given Range in Python

There are several ways to print odd numbers in the given range in Python some of them are:

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Method #1:Using for loop(Static Input)

Approach:

  • Give the lower limit and upper limit as static input and store them in two separate variables.
  • Loop from lower limit range to upper limit range using For loop.
  • Check if the iterator value is even or odd using the if statement and modulus operator.
  • If the iterator value is odd then print it.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit and upper limit as static input
# and store them in two separate variables.
# given lower limit range
lowLimitRange = 23
# given upper limit range
uppLimitRange = 143
print('Odd numbers from', lowLimitRange, 'to', uppLimitRange, 'are :')
# Loop from lower limit range to upper limit range using For loop.
for iterval in range(lowLimitRange, uppLimitRange+1):
    # Check if the iterator value is even or odd using if statement and modulus operator.
    if(iterval % 2 != 0):
        # If the iterator value is odd then print it.
        print(iterval, end=" ")

Output:

Odd numbers from 23 to 143 are :
23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95
97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143

Method #2:Using for loop(User Input separated by spaces)

Approach:

  • Give the lower limit and upper limit as user input separated by spaces using map(), split() functions, and store them in two separate variables.
  • Loop from lower limit range to upper limit range using For loop.
  • Check if the iterator value is even or odd using the if statement and modulus operator.
  • If the iterator value is odd then print it.
  • The Exit of the program.

Below is the implementation:

# Give the lower limit and upper limit as user input separated by spaces using map(),split()
# functions and store them in two separate variables.
lowLimitRange, uppLimitRange = map(int, input(
    'Enter lower limit range and upper limit range separated by spaces = ').split())
print('Odd numbers from', lowLimitRange, 'to', uppLimitRange, 'are :')
# Loop from lower limit range to upper limit range using For loop.
for iterval in range(lowLimitRange, uppLimitRange+1):
    # Check if the iterator value is even or odd using if statement and modulus operator.
    if(iterval % 2 != 0):
        # If the iterator value is odd then print it.
        print(iterval, end=" ")

Output:

Enter lower limit range and upper limit range separated by spaces = 74 446
Odd numbers from 74 to 446 are :
75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 109 111 113 115 117 119 121 123 125 127 129 131 133
 135 137 139 141 143 145 147 149 151 153 155 157 159 161 163 165 167 169 171 173 175 177 179 181 183 185 
187 189 191 193 195 197 199 201 203 205 207 209 211 213 215 217 219 221 223 225 227 229 231 233 235 237 
239 241 243 245 247 249 251 253 255 257 259 261 263 265 267 269 271 273 275 277 279 281 283 285 287 289 
291 293 295 297 299 301 303 305 307 309 311 313 315 317 319 321 323 325 327 329 331 333 335 337 339 341 
343 345 347 349 351 353 355 357 359 361 363 365 367 369 371 373 375 377 379 381 383 385 387 389 391 393
 395 397 399 401 403 405 407 409 411 413 415 417 419 421 423 425 427 429 431 433 435 437 439 441 443 445

Explanation:

  • The user must enter the upper and lower range limits.
  • The for loop spans from the lower to the top range limit.
  • The expression within the if-statement determines whether or not the remainder generated when the integer is divided by two is one (using the % operator).
  • If the remainder is not equal to zero, the number is odd, and so it is printed.

Method #3:Using While Loop(Static Input)

Approach:

  • Give the lower limit and upper limit as static input and store them in two separate variables.
  • Take a temporary variable and initialize it to a lower limit range.
  • Loop till temporary variable is less than or equal to the upper limit range using while loop.
  • Check if the iterator value is even or odd using the if statement and modulus operator.
  • If the iterator value is odd then print it.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program

Below is the implementation:

# Give the lower limit and upper limit as static input
# and store them in two separate variables.
# given lower limit range
lowLimitRange = 38
# given upper limit range
uppLimitRange = 281
# Take a temporary variable and initialize it to a lower limit range.
tempvar = lowLimitRange
print('Odd numbers from', lowLimitRange, 'to', uppLimitRange, 'are :')
# Loop till temporary variable is less than
# or equal to the upper limit range using while loop.
while(tempvar <= uppLimitRange):
    # Check if the iterator value is even or odd using if statement and modulus operator.
    if(tempvar % 2 != 0):
        # If the iterator value is odd then print it.
        print(tempvar, end=" ")
    # Increase the value of the temporary variable by 1.
    tempvar = tempvar+1

Output:

Odd numbers from 38 to 281 are :
39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 103 105 107 
109 111 113 115 117 119 121 123 125 127 129 131 133 135 137 139 141 143 145 147 149 151 153 155 157 159 
161 163 165 167 169 171 173 175 177 179 181 183 185 187 189 191 193 195 197 199 201 203 205 207 209 211
 213 215 217 219 221 223 225 227 229 231 233 235 237 239 241 243 245 247 249 251 253 255 257 259 261 263 
265 267 269 271 273 275 277 279 281

Method #4:Using While Loop(User Input)

Approach:

  • Give the lower limit and upper limit as user input separated by spaces using map(), split() functions, and store them in two separate variables.
  • Take a temporary variable and initialize it to a lower limit range.
  • Loop till temporary variable is less than or equal to the upper limit range using while loop.
  • Check if the iterator value is even or odd using the if statement and modulus operator.
  • If the iterator value is odd then print it.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program

Below is the implementation:

# Give the lower limit and upper limit as user input separated by spaces using map(),split()
# functions and store them in two separate variables.
lowLimitRange, uppLimitRange = map(int, input(
    'Enter lower limit range and upper limit range separated by spaces = ').split())
# Take a temporary variable and initialize it to a lower limit range.
tempvar = lowLimitRange
print('Odd numbers from', lowLimitRange, 'to', uppLimitRange, 'are :')
# Loop till temporary variable is less than
# or equal to the upper limit range using while loop.
while(tempvar <= uppLimitRange):
    # Check if the iterator value is even or odd using if statement and modulus operator.
    if(tempvar % 2 != 0):
        # If the iterator value is odd then print it.
        print(tempvar, end=" ")
    # Increase the value of the temporary variable by 1.
    tempvar = tempvar+1

Output:

Enter lower limit range and upper limit range separated by spaces = 325 785
Odd numbers from 325 to 785 are :
325 327 329 331 333 335 337 339 341 343 345 347 349 351 353 355 357 359 361 363 365 367 369 371 373 375 
377 379 381 383 385 387 389 391 393 395 397 399 401 403 405 407 409 411 413 415 417 419 421 423 425 427
 429 431 433 435 437 439 441 443 445 447 449 451 453 455 457 459 461 463 465 467 469 471 473 475 477 479
 481 483 485 487 489 491 493 495 497 499 501 503 505 507 509 511 513 515 517 519 521 523 525 527 529 531
 533 535 537 539 541 543 545 547 549 551 553 555 557 559 561 563 565 567 569 571 573 575 577 579 581 583 
585 587 589 591 593 595 597 599 601 603 605 607 609 611 613 615 617 619 621 623 625 627 629 631 633 635 
637 639 641 643 645 647 649 651 653 655 657 659 661 663 665 667 669 671 673 675 677 679 681 683 685 687 
689 691 693 695 697 699 701 703 705 707 709 711 713 715 717 719 721 723 725 727 729 731 733 735 737 739 
741 743 745 747 749 751 753 755 757 759 761 763 765 767 769 771 773 775 777 779 781 783 785

Method #5:Using List Comprehension

Approach:

  • Give the lower limit and upper limit as user input separated by spaces using map(), split() functions, and store them in two separate variables.
  • Using List Comprehension, for loop and if statements add all the odd numbers in the given range into the list.
  • Print the list.
  • The Exit of the Program

Below is the implementation:

# Give the lower limit and upper limit as user input separated by spaces using map(),split()
# functions and store them in two separate variables.
lowLimitRange, uppLimitRange = map(int, input(
    'Enter lower limit range and upper limit range separated by spaces = ').split())
# Using List Comprehension, for loop and if statements
# add all the odd numbers in the given range into the list.
oddnumList = [valu for valu in range(
    lowLimitRange, uppLimitRange+1) if valu % 2 != 0]
print('Odd numbers from', lowLimitRange, 'to', uppLimitRange, 'are :')
# Print the list.
for el in oddnumList:
    print(el, end=' ')

Output:

Enter lower limit range and upper limit range separated by spaces = 25 79
Odd numbers from 25 to 79 are :
25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79

Related Programs:

Python Program to Print Odd Numbers Within a Given Range Read More »

Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers

Python Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers

Given lower limit and upper limit , the objective is to explore the integers in the given range that are divisible by 7 and multiples of 5 in Python.

Examples:

Example1:

Input:

Enter some random lower limit =239
Enter some random lower limit =895

Output:

The number which is divisible by 7 and multiple of 5 :
Number = 245
Number = 280
Number = 315
Number = 350
Number = 385
Number = 420
Number = 455
Number = 490
Number = 525
Number = 560
Number = 595
Number = 630
Number = 665
Number = 700
Number = 735
Number = 770
Number = 805
Number = 840
Number = 875

Example2:

Input:

Enter some random lower limit =219
Enter some random lower limit =989

Output:

The number which is divisible by 7 and multiple of 5 :
Number = 245
Number = 280
Number = 315
Number = 350
Number = 385
Number = 420
Number = 455
Number = 490
Number = 525
Number = 560
Number = 595
Number = 630
Number = 665
Number = 700
Number = 735
Number = 770
Number = 805
Number = 840
Number = 875
Number = 910
Number = 945
Number = 980

Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers in Python

There are numerous approaches to discover the numbers in the specified range that are divisible by 7 and multiples of 5, some of which are as follows:

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Method #1:Using for loop (Static input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Use a for loop that goes from the lower to the upper range using range() function.
  • Then using if conditional statement check whether the given iterator value is divisible by 7 and a multiple of 5.
  • If the if condition statement is true then print it.
  • Exit of Program

Below is the implementation:

# given lower limit range as static input
lowerlimit = 19
# given upper limit range as static input
upperlimit = 1289
# Then using if conditional statement check whether the given
# iterator value is divisible by 7 and a multiple of 5.
print("The number which is divisible by 7 and multiple of 5 :")
for numb in range(lowerlimit, upperlimit+1):
  # If the if condition statement is true then print it.
    if(numb % 7 == 0 and numb % 5 == 0):
        print('Number =',numb)

Output:

The number which is divisible by 7 and multiple of 5 :
Number = 35
Number = 70
Number = 105
Number = 140
Number = 175
Number = 210
Number = 245
Number = 280
Number = 315
Number = 350
Number = 385
Number = 420
Number = 455
Number = 490
Number = 525
Number = 560
Number = 595
Number = 630
Number = 665
Number = 700
Number = 735
Number = 770
Number = 805
Number = 840
Number = 875
Number = 910
Number = 945
Number = 980
Number = 1015
Number = 1050
Number = 1085
Number = 1120
Number = 1155
Number = 1190
Number = 1225
Number = 1260

Method #2:Using for loop (User input)

Approach:

  • Scan the lower limit range and upper limit range as user input using int(input()) which converts string to integer.
  • Use a for loop that goes from the lower to the upper range using range() function.
  • Then using if conditional statement check whether the given iterator value is divisible by 7 and a multiple of 5.
  • If the if condition statement is true then print it.
  • Exit of Program

Below is the implementation:

# Scan lower limit range as user input
lowerlimit = int(input("Enter some random lower limit ="))
# Scan upper limit range as user  input
upperlimit = int(input("Enter some random lower limit ="))
# Then using if conditional statement check whether the given
# iterator value is divisible by 7 and a multiple of 5.
print("The number which is divisible by 7 and multiple of 5 :")
for numb in range(lowerlimit, upperlimit+1):
  # If the if condition statement is true then print it.
    if(numb % 7 == 0 and numb % 5 == 0):
        print('Number =', numb)

Output:

Enter some random lower limit =239
Enter some random lower limit =895
The number which is divisible by 7 and multiple of 5 :
Number = 245
Number = 280
Number = 315
Number = 350
Number = 385
Number = 420
Number = 455
Number = 490
Number = 525
Number = 560
Number = 595
Number = 630
Number = 665
Number = 700
Number = 735
Number = 770
Number = 805
Number = 840
Number = 875

Python Program to Find Those Numbers which are Divisible by 7 and Multiple of 5 in a Given Range of Numbers Read More »