AI Big-O Analyzer | Python

Complexity Analysis of is_prime Function

This input provides a comprehensive analysis of the time and space complexity of the Python function 'is_prime', highlighting best, average, and worst-case scenarios. It also includes an average-case scenario illustration for better understanding.


Empty image or helper icon

Prompt

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

Answer

Complexity Analysis of is_prime Function

Code Inspection

The given Python function is_prime takes an integer n as input and determines whether it is a prime number or not. It does this by iterating through numbers from 2 to n-1 and checking for any divisors.

Time Complexity

  • Best Case: O(1) when n is 2 or 3, as the function checks n <= 1 and directly returns True.
  • Average Case: O(n/2) or simply O(n) as it iterates through approximately n/2 numbers to check for divisibility.
  • Worst Case: O(n) when n is a prime number, as it iterates through all numbers from 2 to n-1.

Space Complexity

The space complexity of the function is O(1) as it uses a constant amount of extra space, irrespective of the input size. It only stores the input n and loop variables.

The most time-consuming part is the loop that iterates through the numbers. If it finds a divisor for n, it exits early, thus making it more efficient for non-prime numbers.

Average-Case Scenario Illustration

For the input n = 1009 (a prime number), the function would iterate through 2 to 1008, resulting in approximately 1007 iterations. Therefore, in the average case, the expected time complexity would be O(n) or approximately O(1007), making it efficient for typical conditions.

This analysis provides a clear understanding of the algorithm's efficiency and scalability, making it valuable for evaluating its performance under different scenarios.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This input provides a comprehensive analysis of the time and space complexity of the Python function 'is_prime', highlighting best, average, and worst-case scenarios. It also includes an average-case scenario illustration for better understanding. This analysis enables thorough evaluation of the algorithm's efficiency and scalability.