This Math
class provides a collection of useful mathematical operations. It includes basic arithmetic functions, advanced calculations like factorial, prime number checks, GCD, LCM, Fibonacci sequence generation, and more.
-
Prime Number Operations:
- Print prime numbers within a specified range.
-
Factorial Calculation:
- Calculate the factorial of a given number.
-
Basic Arithmetic:
- Add, subtract, multiply, divide, and raise numbers to a power.
-
Greatest Common Divisor (GCD):
- Calculate the GCD of two numbers.
-
Least Common Multiple (LCM):
- Calculate the LCM of two numbers.
-
Fibonacci Sequence:
- Generate and print the Fibonacci sequence up to a given number of terms.
No external dependencies are required for this class. Just include the class in your PHP project.
To print all prime numbers between two integers:
Math::printPrimeNumbersInRange(10, 50);
To print the factorial of a number:
Math::printFactorial(5); // Output: Factorial of 5 is: 120
You can perform basic arithmetic operations (addition, subtraction, multiplication, division, power) using the printArithmeticOperation
method.
Math::printArithmeticOperation('add', 10, 5); // Output: 10 + 5 = 15
Math::printArithmeticOperation('subtract', 10, 5); // Output: 10 - 5 = 5
Math::printArithmeticOperation('multiply', 10, 5); // Output: 10 * 5 = 50
Math::printArithmeticOperation('divide', 10, 5); // Output: 10 / 5 = 2
Math::printArithmeticOperation('power', 2, 3); // Output: 2 ^ 3 = 8
To calculate the GCD of two numbers:
echo "GCD of 54 and 24 is: " . Math::gcd(54, 24); // Output: GCD of 54 and 24 is: 6
To calculate the LCM of two numbers:
echo "LCM of 54 and 24 is: " . Math::lcm(54, 24); // Output: LCM of 54 and 24 is: 216
To print the Fibonacci sequence up to a given number of terms:
Math::printFibonacci(10); // Output: Fibonacci sequence up to 10 terms: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
- Division by zero is handled using an
InvalidArgumentException
. - Factorial calculation for negative numbers will also throw an
InvalidArgumentException
.
This project is licensed under the MIT License. See the LICENSE file for more details.
This class was created by A_LiReza_ME.