Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Optimized Prime Number Code

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Optimized Prime Number Code. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Principal Financial Group's Principal Retirement Plan services may need to validate integer identifiers or test values before further processing. Implement an optimized function that determines whether a given integer is prime.

A prime number is an integer greater than 1 with exactly two positive divisors: 1 and itself. Return True for prime inputs and False otherwise.

Formal Specification

Implement is_prime(n), where n is an integer. The function must return a Boolean value:

  • True if n is prime
  • False if n is less than 2 or has a divisor other than 1 and itself

Your solution should avoid checking every integer up to n. Explain why checking possible divisors only through sqrt(n) is sufficient, and optimize the loop by handling even numbers separately.

Constraints

  • 0 <= n <= 10^12
  • n is an integer
  • The result must be a Boolean
  • Do not use a library function that directly tests primality

Function Signature

def is_prime(n):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output