Prime Number Exercise
Learn Test-Driven Development (TDD) for the task of determining if a given integer is a prime number or not:
Definition of Prime Number: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself!
Steps
Understanding the Task: Begin by understanding the problem statement. In this case, the task is to create a function or method that determines whether a given integer is a prime number.
Identifying Test Cases: Identify various test cases to verify the correctness of the prime number checking function. Test cases may include:
Testing for prime numbers (both small and large)
Testing for non-prime numbers
Testing for edge cases such as negative numbers, zero, and one
Writing Failing Tests: Start by writing tests for the identified test cases. These tests should initially fail since we haven't implemented the prime number checking function yet.
Implementing the Naive Logic: Begin implementing the prime number checking function using a simple and straightforward approach. For example, you might start by checking divisibility from 2 up to the number itself.
Making Tests Pass: After writing the failing tests and implementing the initial logic, run the tests. The tests should fail initially because the functionality hasn't been implemented yet. Your goal is to write just enough code to make the failing tests pass.
Refactoring and Optimization: Once the tests pass, refactor the code to improve its efficiency, readability, and maintainability. You can optimize the prime number checking function to make it more efficient.
Iterating the TDD Cycle: Continuously iterate through the TDD cycle of writing failing tests, implementing the functionality, and refactoring the code until all test cases pass and the code is clean and efficient.
Last updated