Calculate the square root of a number to five decimal places, handling edge cases like 0 and 1.
Problem Statement
Design an object-oriented solution that computes the square root of a given non-negative number up to five decimal places, while handling all possible edge cases (such as 0, 1, and invalid inputs).
The design should emphasize accuracy, extensibility, and modularity — making it adaptable to different numeric methods or precision requirements.
🎯 Objective
Design a class-based system that:
The system should support different root calculation strategies (e.g., Newton-Raphson method, binary search method).
✅ Functional Requirements
Input:
Output:
Edge Cases:
Precision:
⚙️ Non-Functional Requirements
Category with Requirement
Accuracy
Must be correct up to specified precision (e.g., 1e−5).
Performance
Efficient for numbers up to 10¹².
Extensibility
Should allow plugging in new algorithms (e.g., Babylonian, Binary Search).
Error Handling
Graceful handling of invalid or extreme inputs.
Testability
Each algorithmic strategy should be independently testable.
🧱 Key Classes
1. SquareRootCalculator
Main entry point for computing square roots.
1
2class SquareRootCalculator {
3 private CalculationStrategy strategy;
4 private int precision;
5
6 public SquareRootCalculator(CalculationStrategy strategy, int precision);
7 public double calculate(double number);
8}2. CalculationStrategy (Interface)
Defines the contract for any algorithm that computes square roots.
1
2interface CalculationStrategy {
3 double compute(double number, int precision);
4}3. NewtonRaphsonStrategy
Implements the Newton-Raphson (Babylonian) method for square root calculation.
1
2class NewtonRaphsonStrategy implements CalculationStrategy {
3 public double compute(double number, int precision);
4}4. BinarySearchStrategy
Implements square root computation using Binary Search (for educational or alternate use).
1
2class BinarySearchStrategy implements CalculationStrategy {
3 public double compute(double number, int precision);
4}5. InvalidInputException
Custom exception class for invalid inputs (e.g., negative numbers).
1
2class InvalidInputException extends Exception {
3 public InvalidInputException(String message);
4}6. SqrtApp
Driver or client class for input/output handling.
1
2class SqrtApp {
3 public static void main(String[] args);
4}🔄 Example Flow
Input:
1
2N = 25
3Precision = 5Process:
Output:
1
2Square root of 25 = 5.00000⚠️ Edge Case Examples
Input and Output with Explanation
0
0.00000
Square root of 0 is 0
1
1.00000
Square root of 1 is 1
2
1.41421
Accurate up to 5 decimal places
-4
Error
Negative input not supported
💾 Extensions
🧠 Key Design Considerations
✅ Example Output
1
2Input: 10
3Output: 3.16228
4
5Input: 0
6Output: 0.00000
7
8Input: -9
9Output: InvalidInputException: Negative numbers are not supported.