Random Number Prime Check and Operation

  • Share this:

Code introduction


This function generates a random number, checks if it is a prime number, and returns the factorial of the number if it is prime, or the square root of the number if it is not.


Technology Stack : The code uses the 'random' and 'math' built-in libraries. It utilizes functions like 'rand_range' to generate a random number within a range, 'sqrt' to calculate the square root, 'factorial' to calculate the factorial, and 'is_prime' to check if a number is prime.

Code Type : Function

Code Difficulty : Advanced


                
                    
import random
import math

def generate_random_number():
    """
    Generate a random number within a specified range.
    """
    def rand_range(low, high):
        return random.randint(low, high)

    def sqrt(x):
        return math.sqrt(x)

    def factorial(x):
        if x == 0:
            return 1
        else:
            return x * factorial(x - 1)

    def is_prime(n):
        if n <= 1:
            return False
        for i in range(2, int(sqrt(n)) + 1):
            if n % i == 0:
                return False
        return True

    result = rand_range(1, 100)
    if is_prime(result):
        return factorial(result)
    else:
        return sqrt(result)