repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/MathBuilder.java
src/main/java/com/thealgorithms/maths/MathBuilder.java
package com.thealgorithms.maths; import java.text.DecimalFormat; import java.util.Random; import java.util.function.BiFunction; import java.util.function.Function; /** * Author: Sadiul Hakim : https://github.com/sadiul-hakim * Profession: Backend Engineer * Date: Oct 20, 2024 */ public final class MathBuilder { private final double result; private MathBuilder(Builder builder) { this.result = builder.number; } // Returns final result public double get() { return result; } // Return result in long public long toLong() { try { if (Double.isNaN(result)) { throw new IllegalArgumentException("Cannot convert NaN to long!"); } if (result == Double.POSITIVE_INFINITY) { return Long.MAX_VALUE; } if (result == Double.NEGATIVE_INFINITY) { return Long.MIN_VALUE; } if (result > Long.MAX_VALUE) { return Long.MAX_VALUE; } if (result < Long.MIN_VALUE) { return Long.MIN_VALUE; } return Math.round(result); } catch (Exception ex) { return 0; } } public static class Builder { private double number; private double sideNumber; private boolean inParenthesis; private double memory = 0; public Builder() { number = 0; } public Builder(double num) { number = num; } public Builder add(double num) { if (inParenthesis) { sideNumber += num; } else { number += num; } return this; } // Takes a number and a condition, only does the operation if condition is true. public Builder addIf(double num, BiFunction<Double, Double, Boolean> condition) { if (!condition.apply(number, num)) { return this; } if (inParenthesis) { sideNumber += num; } else { number += num; } return this; } public Builder minus(double num) { if (inParenthesis) { sideNumber -= num; } else { number -= num; } return this; } // Takes a number and a condition, only does the operation if condition is true. public Builder minusIf(double num, BiFunction<Double, Double, Boolean> condition) { if (!condition.apply(number, num)) { return this; } if (inParenthesis) { sideNumber -= num; } else { number -= num; } return this; } // Generates a random number and sets to NUMBER public Builder rand(long seed) { if (number != 0) { throw new RuntimeException("Number must be zero for random assignment!"); } Random random = new Random(); number = random.nextDouble(seed); return this; } // Takes PI value and sets to NUMBER public Builder pi() { if (number != 0) { throw new RuntimeException("Number must be zero for PI assignment!"); } number = Math.PI; return this; } // Takes E value and sets to NUMBER public Builder e() { if (number != 0) { throw new RuntimeException("Number must be zero for E assignment!"); } number = Math.E; return this; } public Builder randomInRange(double min, double max) { if (number != 0) { throw new RuntimeException("Number must be zero for random assignment!"); } Random random = new Random(); number = min + (max - min) * random.nextDouble(); return this; } public Builder toDegrees() { if (inParenthesis) { sideNumber = Math.toDegrees(sideNumber); } else { number = Math.toDegrees(number); } return this; } public Builder max(double num) { if (inParenthesis) { sideNumber = Math.max(sideNumber, num); } else { number = Math.max(number, num); } return this; } public Builder min(double num) { if (inParenthesis) { sideNumber = Math.min(sideNumber, num); } else { number = Math.min(number, num); } return this; } public Builder multiply(double num) { if (inParenthesis) { sideNumber *= num; } else { number *= num; } return this; } // Takes a number and a condition, only does the operation if condition is true. public Builder multiplyIf(double num, BiFunction<Double, Double, Boolean> condition) { if (!condition.apply(number, num)) { return this; } if (inParenthesis) { sideNumber *= num; } else { number *= num; } return this; } public Builder divide(double num) { if (num == 0) { return this; } if (inParenthesis) { sideNumber /= num; } else { number /= num; } return this; } // Takes a number and a condition, only does the operation if condition is true. public Builder divideIf(double num, BiFunction<Double, Double, Boolean> condition) { if (num == 0) { return this; } if (!condition.apply(number, num)) { return this; } if (inParenthesis) { sideNumber /= num; } else { number /= num; } return this; } public Builder mod(double num) { if (inParenthesis) { sideNumber %= num; } else { number %= num; } return this; } // Takes a number and a condition, only does the operation if condition is true. public Builder modIf(double num, BiFunction<Double, Double, Boolean> condition) { if (!condition.apply(number, num)) { return this; } if (inParenthesis) { sideNumber %= num; } else { number %= num; } return this; } public Builder pow(double num) { if (inParenthesis) { sideNumber = Math.pow(sideNumber, num); } else { number = Math.pow(number, num); } return this; } public Builder sqrt() { if (inParenthesis) { sideNumber = Math.sqrt(sideNumber); } else { number = Math.sqrt(number); } return this; } public Builder round() { if (inParenthesis) { sideNumber = Math.round(sideNumber); } else { number = Math.round(number); } return this; } public Builder floor() { if (inParenthesis) { sideNumber = Math.floor(sideNumber); } else { number = Math.floor(number); } return this; } public Builder ceil() { if (inParenthesis) { sideNumber = Math.ceil(sideNumber); } else { number = Math.ceil(number); } return this; } public Builder abs() { if (inParenthesis) { sideNumber = Math.abs(sideNumber); } else { number = Math.abs(number); } return this; } public Builder cbrt() { if (inParenthesis) { sideNumber = Math.cbrt(sideNumber); } else { number = Math.cbrt(number); } return this; } public Builder log() { if (inParenthesis) { sideNumber = Math.log(sideNumber); } else { number = Math.log(number); } return this; } public Builder log10() { if (inParenthesis) { sideNumber = Math.log10(sideNumber); } else { number = Math.log10(number); } return this; } public Builder sin() { if (inParenthesis) { sideNumber = Math.sin(sideNumber); } else { number = Math.sin(number); } return this; } public Builder cos() { if (inParenthesis) { sideNumber = Math.cos(sideNumber); } else { number = Math.cos(number); } return this; } public Builder tan() { if (inParenthesis) { sideNumber = Math.tan(sideNumber); } else { number = Math.tan(number); } return this; } public Builder sinh() { if (inParenthesis) { sideNumber = Math.sinh(sideNumber); } else { number = Math.sinh(number); } return this; } public Builder cosh() { if (inParenthesis) { sideNumber = Math.cosh(sideNumber); } else { number = Math.cosh(number); } return this; } public Builder tanh() { if (inParenthesis) { sideNumber = Math.tanh(sideNumber); } else { number = Math.tanh(number); } return this; } public Builder exp() { if (inParenthesis) { sideNumber = Math.exp(sideNumber); } else { number = Math.exp(number); } return this; } public Builder toRadians() { if (inParenthesis) { sideNumber = Math.toRadians(sideNumber); } else { number = Math.toRadians(number); } return this; } // Remembers the NUMBER public Builder remember() { memory = number; return this; } // Recalls the NUMBER public Builder recall(boolean cleanMemory) { number = memory; if (cleanMemory) { memory = 0; } return this; } // Recalls the NUMBER on condition public Builder recallIf(Function<Double, Boolean> condition, boolean cleanMemory) { if (!condition.apply(number)) { return this; } number = memory; if (cleanMemory) { memory = 0; } return this; } // Replaces NUMBER with given number public Builder set(double num) { if (number != 0) { throw new RuntimeException("Number must be zero to set!"); } number = num; return this; } // Replaces NUMBER with given number on condition public Builder setIf(double num, BiFunction<Double, Double, Boolean> condition) { if (number != 0) { throw new RuntimeException("Number must be zero to set!"); } if (condition.apply(number, num)) { number = num; } return this; } // Prints current NUMBER public Builder print() { System.out.println("MathBuilder Result :: " + number); return this; } public Builder openParenthesis(double num) { sideNumber = num; inParenthesis = true; return this; } public Builder closeParenthesisAndPlus() { number += sideNumber; inParenthesis = false; sideNumber = 0; return this; } public Builder closeParenthesisAndMinus() { number -= sideNumber; inParenthesis = false; sideNumber = 0; return this; } public Builder closeParenthesisAndMultiply() { number *= sideNumber; inParenthesis = false; sideNumber = 0; return this; } public Builder closeParenthesisAndDivide() { number /= sideNumber; inParenthesis = false; sideNumber = 0; return this; } public Builder format(String format) { DecimalFormat formater = new DecimalFormat(format); String num = formater.format(number); number = Double.parseDouble(num); return this; } public Builder format(int decimalPlace) { String pattern = "." + "#".repeat(decimalPlace); DecimalFormat formater = new DecimalFormat(pattern); String num = formater.format(number); number = Double.parseDouble(num); return this; } public MathBuilder build() { return new MathBuilder(this); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Gaussian.java
src/main/java/com/thealgorithms/maths/Gaussian.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; public final class Gaussian { private Gaussian() { } public static ArrayList<Double> gaussian(int matSize, List<Double> matrix) { int i; int j = 0; double[][] mat = new double[matSize + 1][matSize + 1]; double[][] x = new double[matSize][matSize + 1]; // Values from arraylist to matrix for (i = 0; i < matSize; i++) { for (j = 0; j <= matSize; j++) { mat[i][j] = matrix.get(i); } } mat = gaussianElimination(matSize, i, mat); return valueOfGaussian(matSize, x, mat); } // Perform Gaussian elimination public static double[][] gaussianElimination(int matSize, int i, double[][] mat) { int step = 0; for (step = 0; step < matSize - 1; step++) { for (i = step; i < matSize - 1; i++) { double a = (mat[i + 1][step] / mat[step][step]); for (int j = step; j <= matSize; j++) { mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]); } } } return mat; } // calculate the x_1, x_2, ... values of the gaussian and save it in an arraylist. public static ArrayList<Double> valueOfGaussian(int matSize, double[][] x, double[][] mat) { ArrayList<Double> answerArray = new ArrayList<Double>(); int i; int j; for (i = 0; i < matSize; i++) { for (j = 0; j <= matSize; j++) { x[i][j] = mat[i][j]; } } for (i = matSize - 1; i >= 0; i--) { double sum = 0; for (j = matSize - 1; j > i; j--) { x[i][j] = x[j][j] * x[i][j]; sum = x[i][j] + sum; } if (x[i][i] == 0) { x[i][i] = 0; } else { x[i][i] = (x[i][matSize] - sum) / (x[i][i]); } answerArray.add(x[i][j]); } return answerArray; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/JugglerSequence.java
src/main/java/com/thealgorithms/maths/JugglerSequence.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; /* * Java program for printing juggler sequence * Wikipedia: https://en.wikipedia.org/wiki/Juggler_sequence * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class JugglerSequence { private JugglerSequence() { } /** * This method prints juggler sequence starting with the number in the parameter * * @param inputNumber Number from which juggler sequence is to be started */ public static void jugglerSequence(int inputNumber) { // Copy method argument to a local variable int n = inputNumber; List<String> seq = new ArrayList<>(); seq.add(n + ""); // Looping till n reaches 1 while (n != 1) { int temp; // if previous term is even then // next term in the sequence is square root of previous term // if previous term is odd then // next term is floor value of 3 time the square root of previous term // Check if previous term is even or odd if (n % 2 == 0) { temp = (int) Math.floor(Math.sqrt(n)); } else { temp = (int) Math.floor(Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)); } n = temp; seq.add(n + ""); } String res = String.join(",", seq); System.out.print(res + "\n"); } // Driver code public static void main(String[] args) { jugglerSequence(3); // Output: 3,5,11,36,6,2,1 } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AmicableNumber.java
src/main/java/com/thealgorithms/maths/AmicableNumber.java
package com.thealgorithms.maths; import java.util.LinkedHashSet; import java.util.Set; import org.apache.commons.lang3.tuple.Pair; /** * Amicable numbers are two different natural numbers that the sum of the * proper divisors of each is equal to the other number. * (A proper divisor of a number is a positive factor of that number other than the number itself. * For example, the proper divisors of 6 are 1, 2, and 3.) * A pair of amicable numbers constitutes an aliquot sequence of period 2. * It is unknown if there are infinitely many pairs of amicable numbers. * * <p> * link: https://en.wikipedia.org/wiki/Amicable_numbers * <p> * Simple Example: (220, 284) * 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110} <-SUM = 284 * 284 is divisible by {1,2,4,71,142} <-SUM = 220. */ public final class AmicableNumber { private AmicableNumber() { } /** * Finds all the amicable numbers in a given range. * * @param from range start value * @param to range end value (inclusive) * @return list with amicable numbers found in given range. */ public static Set<Pair<Integer, Integer>> findAllInRange(int from, int to) { if (from <= 0 || to <= 0 || to < from) { throw new IllegalArgumentException("Given range of values is invalid!"); } Set<Pair<Integer, Integer>> result = new LinkedHashSet<>(); for (int i = from; i < to; i++) { for (int j = i + 1; j <= to; j++) { if (isAmicableNumber(i, j)) { result.add(Pair.of(i, j)); } } } return result; } /** * Checks whether 2 numbers are AmicableNumbers or not. */ public static boolean isAmicableNumber(int a, int b) { if (a <= 0 || b <= 0) { throw new IllegalArgumentException("Input numbers must be natural!"); } return sumOfDividers(a, a) == b && sumOfDividers(b, b) == a; } /** * Recursively calculates the sum of all dividers for a given number excluding the divider itself. */ private static int sumOfDividers(int number, int divisor) { if (divisor == 1) { return 0; } else if (number % --divisor == 0) { return sumOfDividers(number, divisor) + divisor; } else { return sumOfDividers(number, divisor); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/HappyNumber.java
src/main/java/com/thealgorithms/maths/HappyNumber.java
package com.thealgorithms.maths; /** * A Happy Number is defined as a number which eventually reaches 1 when replaced * by the sum of the squares of each digit. * If it falls into a cycle that does not include 1, then it is not a happy number. * Example: * 19 → 1² + 9² = 82 * 82 → 8² + 2² = 68 * 68 → 6² + 8² = 100 * 100 → 1² + 0² + 0² = 1 → Happy Number! */ public final class HappyNumber { private HappyNumber() { } /** * Checks whether the given number is a Happy Number. * Uses Floyd’s Cycle Detection algorithm (tortoise and hare method) * to detect loops efficiently. * * @param n The number to check * @return true if n is a Happy Number, false otherwise */ public static boolean isHappy(int n) { int slow = n; int fast = n; do { slow = sumOfSquares(slow); // move 1 step fast = sumOfSquares(sumOfSquares(fast)); // move 2 steps } while (slow != fast); return slow == 1; // If cycle ends in 1 → Happy number } /** * Calculates the sum of squares of the digits of a number. * * Example: * num = 82 → 8² + 2² = 64 + 4 = 68 * * @param num The number to calculate sum of squares of digits * @return The sum of squares of the digits */ private static int sumOfSquares(int num) { int sum = 0; while (num > 0) { int digit = num % 10; sum += digit * digit; num /= 10; } return sum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LeonardoNumber.java
src/main/java/com/thealgorithms/maths/LeonardoNumber.java
package com.thealgorithms.maths; /** * Utility class for calculating Leonardo Numbers. * <p> * Leonardo numbers are a sequence of numbers defined by the recurrence: * L(n) = L(n-1) + L(n-2) + 1, with L(0) = 1 and L(1) = 1 * <p> * The sequence begins: 1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, ... * <p> * This class provides both a recursive implementation and an optimized * iterative * implementation for calculating Leonardo numbers. * * @see <a href="https://en.wikipedia.org/wiki/Leonardo_number">Leonardo Number * - Wikipedia</a> * @see <a href="https://oeis.org/A001595">OEIS A001595</a> */ public final class LeonardoNumber { private LeonardoNumber() { } /** * Calculates the nth Leonardo Number using recursion. * <p> * Time Complexity: O(2^n) - exponential due to repeated calculations * Space Complexity: O(n) - due to recursion stack * <p> * Note: This method is not recommended for large values of n due to exponential * time complexity. * Consider using {@link #leonardoNumberIterative(int)} for better performance. * * @param n the index of the Leonardo Number to calculate (must be non-negative) * @return the nth Leonardo Number * @throws IllegalArgumentException if n is negative */ public static int leonardoNumber(int n) { if (n < 0) { throw new IllegalArgumentException("Input must be non-negative. Received: " + n); } if (n == 0 || n == 1) { return 1; } return leonardoNumber(n - 1) + leonardoNumber(n - 2) + 1; } /** * Calculates the nth Leonardo Number using an iterative approach. * <p> * This method provides better performance than the recursive version for large * values of n. * <p> * Time Complexity: O(n) * Space Complexity: O(1) * * @param n the index of the Leonardo Number to calculate (must be non-negative) * @return the nth Leonardo Number * @throws IllegalArgumentException if n is negative */ public static int leonardoNumberIterative(int n) { if (n < 0) { throw new IllegalArgumentException("Input must be non-negative. Received: " + n); } if (n == 0 || n == 1) { return 1; } int previous = 1; int current = 1; for (int i = 2; i <= n; i++) { int next = current + previous + 1; previous = current; current = next; } return current; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java
src/main/java/com/thealgorithms/maths/SquareRootWithBabylonianMethod.java
package com.thealgorithms.maths; public final class SquareRootWithBabylonianMethod { private SquareRootWithBabylonianMethod() { } /** * get the value, return the square root * * @param num contains elements * @return the square root of num */ public static float squareRoot(float num) { float a = num; float b = 1; double e = 0.000001; while (a - b > e) { a = (a + b) / 2; b = num / a; } return a; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/UniformNumbers.java
src/main/java/com/thealgorithms/maths/UniformNumbers.java
package com.thealgorithms.maths; /** * A positive integer is considered uniform if all * of its digits are equal. For example, 222 is uniform, * while 223 is not. * Given two positive integers a and b, determine the * number of uniform integers between a and b. */ public final class UniformNumbers { // Private constructor to prevent instantiation of the utility class private UniformNumbers() { // Prevent instantiation } /** * This function will find the number of uniform numbers * from 1 to num * @param num upper limit to find the uniform numbers * @return the count of uniform numbers between 1 and num */ public static int uniformNumbers(int num) { String numStr = Integer.toString(num); int uniformCount = (numStr.length() - 1) * 9; int finalUniform = Integer.parseInt(String.valueOf(numStr.charAt(0)).repeat(numStr.length())); if (finalUniform <= num) { uniformCount += Integer.parseInt(String.valueOf(numStr.charAt(0))); } else { uniformCount += Integer.parseInt(String.valueOf(numStr.charAt(0))) - 1; } return uniformCount; } /** * This function will calculate the number of uniform numbers * between a and b * @param a lower bound of range * @param b upper bound of range * @return the count of uniform numbers between a and b */ public static int countUniformIntegers(int a, int b) { if (b > a && b > 0 && a > 0) { return uniformNumbers(b) - uniformNumbers(a - 1); } else if (b == a) { return 1; } else { return 0; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/JosephusProblem.java
src/main/java/com/thealgorithms/maths/JosephusProblem.java
package com.thealgorithms.maths; /** * There are n friends that are playing a game. The friends are sitting in a circle and are * numbered from 1 to n in clockwise order. More formally, moving clockwise from the ith friend * brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings * you to the 1st friend. The rules of the game are as follows: 1.Start at the 1st friend. 2.Count the next k friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once. 3.The last friend you counted leaves the circle and loses the game. 4.If there is still more than one friend in the circle, go back to step 2 starting from the friend immediately clockwise of the friend who just lost and repeat. 5.Else, the last friend in the circle wins the game. @author Kunal */ public final class JosephusProblem { private JosephusProblem() { } /** * Find the Winner of the Circular Game. * * @param number of friends, n, and an integer k * @return return the winner of the game */ public static int findTheWinner(int n, int k) { return winner(n, k) + 1; } public static int winner(int n, int k) { if (n == 1) { return 0; } return (winner(n - 1, k) + k) % n; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PronicNumber.java
src/main/java/com/thealgorithms/maths/PronicNumber.java
package com.thealgorithms.maths; /* * Java program for Pronic Number * Pronic Number: A number n is a pronic number if * it is equal to product of two consecutive numbers m and m+1. * Wikipedia: https://en.wikipedia.org/wiki/Pronic_number * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class PronicNumber { private PronicNumber() { } /** * This method checks if the given number is pronic number or non-pronic number * * @param inputNumber Integer value which is to be checked if is a pronic number or not * @return true if input number is a pronic number, false otherwise */ static boolean isPronic(int inputNumber) { if (inputNumber == 0) { return true; } // Iterating from 0 to input_number for (int i = 0; i <= inputNumber; i++) { // Checking if product of i and (i+1) is equals input_number if (i * (i + 1) == inputNumber && i != inputNumber) { // return true if product of i and (i+1) is equals input_number return true; } } // return false if product of i and (i+1) for all values from 0 to input_number is not // equals input_number return false; } /** * This method checks if the given number is pronic number or non-pronic number using square root of number for finding divisors * * @param number Integer value which is to be checked if is a pronic number or not * @return true if input number is a pronic number, false otherwise */ public static boolean isPronicNumber(int number) { int squareRoot = (int) Math.sqrt(number); // finding just smaller divisor of the number than its square root. return squareRoot * (squareRoot + 1) == number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/NthUglyNumber.java
src/main/java/com/thealgorithms/maths/NthUglyNumber.java
package com.thealgorithms.maths; import static java.util.Collections.singletonList; import java.util.ArrayList; import java.util.Map; import org.apache.commons.lang3.tuple.MutablePair; /** * @brief class computing the n-th ugly number (when they are sorted) * @details the ugly numbers with base [2, 3, 5] are all numbers of the form 2^a*3^b^5^c, * where the exponents a, b, c are non-negative integers. * Some properties of ugly numbers: * - base [2, 3, 5] ugly numbers are the 5-smooth numbers, cf. https://oeis.org/A051037 * - base [2, 3, 5, 7] ugly numbers are 7-smooth numbers, cf. https://oeis.org/A002473 * - base [2] ugly numbers are the non-negative powers of 2, * - the base [2, 3, 5] ugly numbers are the same as base [5, 6, 2, 3, 5] ugly numbers */ public class NthUglyNumber { private ArrayList<Long> uglyNumbers = new ArrayList<>(singletonList(1L)); private ArrayList<MutablePair<Integer, Integer>> positions = new ArrayList<>(); /** * @brief initialized the object allowing to compute ugly numbers with given base * @param baseNumbers the given base of ugly numbers * @exception IllegalArgumentException baseNumber is empty */ NthUglyNumber(final int[] baseNumbers) { if (baseNumbers.length == 0) { throw new IllegalArgumentException("baseNumbers must be non-empty."); } for (final var baseNumber : baseNumbers) { this.positions.add(MutablePair.of(baseNumber, 0)); } } /** * @param n the zero-based-index of the queried ugly number * @exception IllegalArgumentException n is negative * @return the n-th ugly number (starting from index 0) */ public Long get(final int n) { if (n < 0) { throw new IllegalArgumentException("n must be non-negative."); } while (uglyNumbers.size() <= n) { addUglyNumber(); } return uglyNumbers.get(n); } private void addUglyNumber() { uglyNumbers.add(computeMinimalCandidate()); updatePositions(); } private void updatePositions() { final var lastUglyNumber = uglyNumbers.get(uglyNumbers.size() - 1); for (var entry : positions) { if (computeCandidate(entry) == lastUglyNumber) { entry.setValue(entry.getValue() + 1); } } } private long computeCandidate(final Map.Entry<Integer, Integer> entry) { return entry.getKey() * uglyNumbers.get(entry.getValue()); } private long computeMinimalCandidate() { long res = Long.MAX_VALUE; for (final var entry : positions) { res = Math.min(res, computeCandidate(entry)); } return res; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FrizzyNumber.java
src/main/java/com/thealgorithms/maths/FrizzyNumber.java
package com.thealgorithms.maths; /** * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> * Program description - To find the FrizzyNumber */ public final class FrizzyNumber { private FrizzyNumber() { } /** * Returns the n-th number that is a sum of powers * of the given base. * Example: base = 3 and n = 4 * Ascending order of sums of powers of 3 = * 3^0 = 1, 3^1 = 3, 3^1 + 3^0 = 4, 3^2 + 3^0 = 9 * Ans = 9 * * @param base The base whose n-th sum of powers is required * @param n Index from ascending order of sum of powers of base * @return n-th sum of powers of base */ public static double getNthFrizzy(int base, int n) { double final1 = 0.0; int i = 0; do { final1 += Math.pow(base, i++) * (n % 2); } while ((n /= 2) > 0); return final1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PythagoreanTriple.java
src/main/java/com/thealgorithms/maths/PythagoreanTriple.java
package com.thealgorithms.maths; /** * Utility class to check if three integers form a Pythagorean triple. * A Pythagorean triple consists of three positive integers a, b, and c, * such that a² + b² = c². * * Common examples: * - (3, 4, 5) * - (5, 12, 13) * * Reference: https://en.wikipedia.org/wiki/Pythagorean_triple */ public final class PythagoreanTriple { private PythagoreanTriple() { } /** * Checks whether three integers form a Pythagorean triple. * The order of parameters does not matter. * * @param a one side length * @param b another side length * @param c another side length * @return {@code true} if (a, b, c) can form a Pythagorean triple, otherwise {@code false} */ public static boolean isPythagTriple(int a, int b, int c) { if (a <= 0 || b <= 0 || c <= 0) { return false; } // Sort the sides so the largest is treated as hypotenuse int[] sides = {a, b, c}; java.util.Arrays.sort(sides); int x = sides[0]; int y = sides[1]; int hypotenuse = sides[2]; return x * x + y * y == hypotenuse * hypotenuse; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/GermainPrimeAndSafePrime.java
src/main/java/com/thealgorithms/maths/GermainPrimeAndSafePrime.java
package com.thealgorithms.maths; import com.thealgorithms.maths.Prime.PrimeCheck; /** * A utility class to check whether a number is a Germain prime or a Safe prime. * * <p>This class provides methods to: * <ul> * <li>Check if a number is a Germain prime</li> * <li>Check if a number is a Safe prime</li> * </ul> * * <p>Definitions: * <ul> * <li>A Germain prime is a prime number p such that 2p + 1 is also prime.</li> * <li>A Safe prime is a prime number p such that (p - 1) / 2 is also prime.</li> * </ul> * * <p>This class is final and cannot be instantiated. * * @see <a href="https://en.wikipedia.org/wiki/Safe_and_Sophie_Germain_primes">Wikipedia: Safe and Sophie Germain primes</a> */ public final class GermainPrimeAndSafePrime { // Private constructor to prevent instantiation private GermainPrimeAndSafePrime() { } /** * Checks if a number is a Germain prime. * * <p>A Germain prime is a prime number p such that 2p + 1 is also prime. * * @param number the number to check; must be a positive integer * @return {@code true} if the number is a Germain prime, {@code false} otherwise * @throws IllegalArgumentException if the input number is less than 1 */ public static boolean isGermainPrime(int number) { if (number < 1) { throw new IllegalArgumentException("Input value must be a positive integer. Input value: " + number); } // A number is a Germain prime if it is prime and 2 * number + 1 is also prime return PrimeCheck.isPrime(number) && PrimeCheck.isPrime(2 * number + 1); } /** * Checks if a number is a Safe prime. * * <p>A Safe prime is a prime number p such that (p - 1) / 2 is also prime. * * @param number the number to check; must be a positive integer * @return {@code true} if the number is a Safe prime, {@code false} otherwise * @throws IllegalArgumentException if the input number is less than 1 */ public static boolean isSafePrime(int number) { if (number < 1) { throw new IllegalArgumentException("Input value must be a positive integer. Input value: " + number); } // A number is a Safe prime if it is prime, (number - 1) is even, and (number - 1) / 2 is prime return ((number - 1) % 2 == 0) && PrimeCheck.isPrime(number) && PrimeCheck.isPrime((number - 1) / 2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ChebyshevIteration.java
src/main/java/com/thealgorithms/maths/ChebyshevIteration.java
package com.thealgorithms.maths; /** * In numerical analysis, Chebyshev iteration is an iterative method for solving * systems of linear equations Ax = b. It is designed for systems where the * matrix A is symmetric positive-definite (SPD). * * <p> * This method is a "polynomial acceleration" method, meaning it finds the * optimal polynomial to apply to the residual to accelerate convergence. * * <p> * It requires knowledge of the bounds of the eigenvalues of the matrix A: * m(A) (smallest eigenvalue) and M(A) (largest eigenvalue). * * <p> * Wikipedia: https://en.wikipedia.org/wiki/Chebyshev_iteration * * @author Mitrajit Ghorui(KeyKyrios) */ public final class ChebyshevIteration { private ChebyshevIteration() { } /** * Solves the linear system Ax = b using the Chebyshev iteration method. * * <p> * NOTE: The matrix A *must* be symmetric positive-definite (SPD) for this * algorithm to converge. * * @param a The matrix A (must be square, SPD). * @param b The vector b. * @param x0 The initial guess vector. * @param minEigenvalue The smallest eigenvalue of A (m(A)). * @param maxEigenvalue The largest eigenvalue of A (M(A)). * @param maxIterations The maximum number of iterations to perform. * @param tolerance The desired tolerance for the residual norm. * @return The solution vector x. * @throws IllegalArgumentException if matrix/vector dimensions are * incompatible, * if maxIterations <= 0, or if eigenvalues are invalid (e.g., minEigenvalue * <= 0, maxEigenvalue <= minEigenvalue). */ public static double[] solve(double[][] a, double[] b, double[] x0, double minEigenvalue, double maxEigenvalue, int maxIterations, double tolerance) { validateInputs(a, b, x0, minEigenvalue, maxEigenvalue, maxIterations, tolerance); int n = b.length; double[] x = x0.clone(); double[] r = vectorSubtract(b, matrixVectorMultiply(a, x)); double[] p = new double[n]; double d = (maxEigenvalue + minEigenvalue) / 2.0; double c = (maxEigenvalue - minEigenvalue) / 2.0; double alpha = 0.0; double alphaPrev = 0.0; for (int k = 0; k < maxIterations; k++) { double residualNorm = vectorNorm(r); if (residualNorm < tolerance) { return x; // Solution converged } if (k == 0) { alpha = 1.0 / d; System.arraycopy(r, 0, p, 0, n); // p = r } else { double beta = c * alphaPrev / 2.0 * (c * alphaPrev / 2.0); alpha = 1.0 / (d - beta / alphaPrev); double[] pUpdate = scalarMultiply(beta / alphaPrev, p); p = vectorAdd(r, pUpdate); // p = r + (beta / alphaPrev) * p } double[] xUpdate = scalarMultiply(alpha, p); x = vectorAdd(x, xUpdate); // x = x + alpha * p // Recompute residual for accuracy r = vectorSubtract(b, matrixVectorMultiply(a, x)); alphaPrev = alpha; } return x; // Return best guess after maxIterations } /** * Validates the inputs for the Chebyshev solver. */ private static void validateInputs(double[][] a, double[] b, double[] x0, double minEigenvalue, double maxEigenvalue, int maxIterations, double tolerance) { int n = a.length; if (n == 0) { throw new IllegalArgumentException("Matrix A cannot be empty."); } if (n != a[0].length) { throw new IllegalArgumentException("Matrix A must be square."); } if (n != b.length) { throw new IllegalArgumentException("Matrix A and vector b dimensions do not match."); } if (n != x0.length) { throw new IllegalArgumentException("Matrix A and vector x0 dimensions do not match."); } if (minEigenvalue <= 0) { throw new IllegalArgumentException("Smallest eigenvalue must be positive (matrix must be positive-definite)."); } if (maxEigenvalue <= minEigenvalue) { throw new IllegalArgumentException("Max eigenvalue must be strictly greater than min eigenvalue."); } if (maxIterations <= 0) { throw new IllegalArgumentException("Max iterations must be positive."); } if (tolerance <= 0) { throw new IllegalArgumentException("Tolerance must be positive."); } } // --- Vector/Matrix Helper Methods --- /** * Computes the product of a matrix A and a vector v (Av). */ private static double[] matrixVectorMultiply(double[][] a, double[] v) { int n = a.length; double[] result = new double[n]; for (int i = 0; i < n; i++) { double sum = 0; for (int j = 0; j < n; j++) { sum += a[i][j] * v[j]; } result[i] = sum; } return result; } /** * Computes the subtraction of two vectors (v1 - v2). */ private static double[] vectorSubtract(double[] v1, double[] v2) { int n = v1.length; double[] result = new double[n]; for (int i = 0; i < n; i++) { result[i] = v1[i] - v2[i]; } return result; } /** * Computes the addition of two vectors (v1 + v2). */ private static double[] vectorAdd(double[] v1, double[] v2) { int n = v1.length; double[] result = new double[n]; for (int i = 0; i < n; i++) { result[i] = v1[i] + v2[i]; } return result; } /** * Computes the product of a scalar and a vector (s * v). */ private static double[] scalarMultiply(double scalar, double[] v) { int n = v.length; double[] result = new double[n]; for (int i = 0; i < n; i++) { result[i] = scalar * v[i]; } return result; } /** * Computes the L2 norm (Euclidean norm) of a vector. */ private static double vectorNorm(double[] v) { double sumOfSquares = 0; for (double val : v) { sumOfSquares += val * val; } return Math.sqrt(sumOfSquares); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SumOfDigits.java
src/main/java/com/thealgorithms/maths/SumOfDigits.java
package com.thealgorithms.maths; public final class SumOfDigits { private SumOfDigits() { } /** * Calculate the sum of digits of a number * * @param number the number contains digits * @return sum of digits of given {@code number} */ public static int sumOfDigits(int number) { final int base = 10; number = Math.abs(number); int sum = 0; while (number != 0) { sum += number % base; number /= base; } return sum; } /** * Calculate the sum of digits of a number using recursion * * @param number the number contains digits * @return sum of digits of given {@code number} */ public static int sumOfDigitsRecursion(int number) { final int base = 10; number = Math.abs(number); return number < base ? number : number % base + sumOfDigitsRecursion(number / base); } /** * Calculate the sum of digits of a number using char array * * @param number the number contains digits * @return sum of digits of given {@code number} */ public static int sumOfDigitsFast(final int number) { return String.valueOf(Math.abs(number)).chars().map(c -> c - '0').reduce(0, Integer::sum); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/GoldbachConjecture.java
src/main/java/com/thealgorithms/maths/GoldbachConjecture.java
package com.thealgorithms.maths; import static com.thealgorithms.maths.Prime.PrimeCheck.isPrime; /** * This is a representation of the unsolved problem of Goldbach's Projection, according to which every * even natural number greater than 2 can be written as the sum of 2 prime numbers * More info: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture * @author Vasilis Sarantidis (https://github.com/BILLSARAN) */ public final class GoldbachConjecture { private GoldbachConjecture() { } public record Result(int number1, int number2) { } public static Result getPrimeSum(int number) { if (number <= 2 || number % 2 != 0) { throw new IllegalArgumentException("Number must be even and greater than 2."); } for (int i = 0; i <= number / 2; i++) { if (isPrime(i) && isPrime(number - i)) { return new Result(i, number - i); } } throw new IllegalStateException("No valid prime sum found."); // Should not occur } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Pow.java
src/main/java/com/thealgorithms/maths/Pow.java
package com.thealgorithms.maths; /** * A utility class for computing exponentiation (power) of integers. * <p> * This class provides a method to calculate the value of a base raised to a given exponent using a simple iterative approach. * For example, given a base {@code a} and an exponent {@code b}, the class computes {@code a}<sup>{@code b}</sup>. * </p> */ public final class Pow { private Pow() { } /** * Computes the value of the base raised to the power of the exponent. * <p> * The method calculates {@code a}<sup>{@code b}</sup> by iteratively multiplying the base {@code a} with itself {@code b} times. * If the exponent {@code b} is negative, an {@code IllegalArgumentException} is thrown. * </p> * * @param a the base of the exponentiation. Must be a non-negative integer. * @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer. * @return the result of {@code a}<sup>{@code b}</sup> as a {@code long}. * @throws IllegalArgumentException if {@code b} is negative. */ public static long pow(int a, int b) { if (b < 0) { throw new IllegalArgumentException("Exponent must be non-negative."); } long result = 1; for (int i = 1; i <= b; i++) { result *= a; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SumOfSquares.java
src/main/java/com/thealgorithms/maths/SumOfSquares.java
package com.thealgorithms.maths; /** * Implementation of Lagrange's Four Square Theorem * Find minimum number of perfect squares that sum to given number * * @see <a href="https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem">Lagrange's Four Square Theorem</a> * @author BEASTSHRIRAM */ public final class SumOfSquares { private SumOfSquares() { // Utility class } /** * Find minimum number of perfect squares that sum to n * * @param n the target number * @return minimum number of squares needed */ public static int minSquares(int n) { if (isPerfectSquare(n)) { return 1; } for (int i = 1; i * i <= n; i++) { int remaining = n - i * i; if (isPerfectSquare(remaining)) { return 2; } } // Legendre's three-square theorem int temp = n; while (temp % 4 == 0) { temp /= 4; } if (temp % 8 == 7) { return 4; } return 3; } private static boolean isPerfectSquare(int n) { if (n < 0) { return false; } int root = (int) Math.sqrt(n); return root * root == n; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/StandardDeviation.java
src/main/java/com/thealgorithms/maths/StandardDeviation.java
package com.thealgorithms.maths; public final class StandardDeviation { private StandardDeviation() { } public static double stdDev(double[] data) { double variance = 0; double avg = 0; for (int i = 0; i < data.length; i++) { avg += data[i]; } avg /= data.length; for (int j = 0; j < data.length; j++) { variance += Math.pow((data[j] - avg), 2); } variance /= data.length; return Math.sqrt(variance); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java
src/main/java/com/thealgorithms/maths/ExtendedEuclideanAlgorithm.java
package com.thealgorithms.maths; /** * In mathematics, the extended Euclidean algorithm is an extension to the * Euclidean algorithm, and computes, in addition to the greatest common divisor * (gcd) of integers a and b, also the coefficients of Bézout's identity, which * are integers x and y such that ax + by = gcd(a, b). * * <p> * For more details, see * https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm */ public final class ExtendedEuclideanAlgorithm { private ExtendedEuclideanAlgorithm() { } /** * This method implements the extended Euclidean algorithm. * * @param a The first number. * @param b The second number. * @return An array of three integers: * <ul> * <li>Index 0: The greatest common divisor (gcd) of a and b.</li> * <li>Index 1: The value of x in the equation ax + by = gcd(a, b).</li> * <li>Index 2: The value of y in the equation ax + by = gcd(a, b).</li> * </ul> */ public static long[] extendedGCD(long a, long b) { if (b == 0) { // Base case: gcd(a, 0) = a. The equation is a*1 + 0*0 = a. return new long[] {a, 1, 0}; } // Recursive call long[] result = extendedGCD(b, a % b); long gcd = result[0]; long x1 = result[1]; long y1 = result[2]; // Update coefficients using the results from the recursive call long x = y1; long y = x1 - a / b * y1; return new long[] {gcd, x, y}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/HeronsFormula.java
src/main/java/com/thealgorithms/maths/HeronsFormula.java
package com.thealgorithms.maths; /** * Heron's Formula implementation for calculating the area of a triangle given * its three side lengths. * <p> * Heron's Formula states that the area of a triangle whose sides have lengths * a, b, and c is: * Area = √(s(s - a)(s - b)(s - c)) * where s is the semi-perimeter of the triangle: s = (a + b + c) / 2 * </p> * * @see <a href="https://en.wikipedia.org/wiki/Heron%27s_formula">Heron's * Formula - Wikipedia</a> * @author satyabarghav */ public final class HeronsFormula { /** * Private constructor to prevent instantiation of this utility class. */ private HeronsFormula() { } /** * Checks if all three side lengths are positive. * * @param a the length of the first side * @param b the length of the second side * @param c the length of the third side * @return true if all sides are positive, false otherwise */ private static boolean areAllSidesPositive(final double a, final double b, final double c) { return a > 0 && b > 0 && c > 0; } /** * Checks if the given side lengths satisfy the triangle inequality theorem. * <p> * The triangle inequality theorem states that the sum of any two sides * of a triangle must be greater than the third side. * </p> * * @param a the length of the first side * @param b the length of the second side * @param c the length of the third side * @return true if the sides can form a valid triangle, false otherwise */ private static boolean canFormTriangle(final double a, final double b, final double c) { return a + b > c && b + c > a && c + a > b; } /** * Calculates the area of a triangle using Heron's Formula. * <p> * Given three side lengths a, b, and c, the area is computed as: * Area = √(s(s - a)(s - b)(s - c)) * where s is the semi-perimeter: s = (a + b + c) / 2 * </p> * * @param a the length of the first side (must be positive) * @param b the length of the second side (must be positive) * @param c the length of the third side (must be positive) * @return the area of the triangle * @throws IllegalArgumentException if any side length is non-positive or if the * sides cannot form a valid triangle */ public static double herons(final double a, final double b, final double c) { if (!areAllSidesPositive(a, b, c)) { throw new IllegalArgumentException("All side lengths must be positive"); } if (!canFormTriangle(a, b, c)) { throw new IllegalArgumentException("Triangle cannot be formed with the given side lengths (violates triangle inequality)"); } final double s = (a + b + c) / 2.0; return Math.sqrt((s) * (s - a) * (s - b) * (s - c)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/CatalanNumbers.java
src/main/java/com/thealgorithms/maths/CatalanNumbers.java
package com.thealgorithms.maths; /** * Calculate Catalan Numbers */ public final class CatalanNumbers { private CatalanNumbers() { } /** * Calculate the nth Catalan number using a recursive formula. * * @param n the index of the Catalan number to compute * @return the nth Catalan number */ public static long catalan(final int n) { if (n < 0) { throw new IllegalArgumentException("Index must be non-negative"); } return factorial(2 * n) / (factorial(n + 1) * factorial(n)); } /** * Calculate the factorial of a number. * * @param n the number to compute the factorial for * @return the factorial of n */ private static long factorial(final int n) { if (n == 0 || n == 1) { return 1; } long result = 1; for (int i = 2; i <= n; i++) { result *= i; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java
src/main/java/com/thealgorithms/maths/QuadraticEquationSolver.java
package com.thealgorithms.maths; /** * This class represents a complex number which has real and imaginary part */ class ComplexNumber { Double real; Double imaginary; ComplexNumber(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } ComplexNumber(double real) { this.real = real; this.imaginary = null; } } /** * Quadratic Equation Formula is used to find * the roots of a quadratic equation of the form ax^2 + bx + c = 0 * * @see <a href="https://en.wikipedia.org/wiki/Quadratic_equation">Quadratic Equation</a> */ public class QuadraticEquationSolver { /** * Function takes in the coefficients of the quadratic equation * * @param a is the coefficient of x^2 * @param b is the coefficient of x * @param c is the constant * @return roots of the equation which are ComplexNumber type */ public ComplexNumber[] solveEquation(double a, double b, double c) { double discriminant = b * b - 4 * a * c; // if discriminant is positive, roots will be different if (discriminant > 0) { return new ComplexNumber[] {new ComplexNumber((-b + Math.sqrt(discriminant)) / (2 * a)), new ComplexNumber((-b - Math.sqrt(discriminant)) / (2 * a))}; } // if discriminant is zero, roots will be same if (discriminant == 0) { return new ComplexNumber[] {new ComplexNumber((-b) / (2 * a))}; } // if discriminant is negative, roots will have imaginary parts if (discriminant < 0) { double realPart = -b / (2 * a); double imaginaryPart = Math.sqrt(-discriminant) / (2 * a); return new ComplexNumber[] {new ComplexNumber(realPart, imaginaryPart), new ComplexNumber(realPart, -imaginaryPart)}; } // return no roots return new ComplexNumber[] {}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/GenericRoot.java
src/main/java/com/thealgorithms/maths/GenericRoot.java
package com.thealgorithms.maths; /** * Calculates the generic root (repeated digital sum) of a non-negative integer. * <p> * For example, the generic root of 12345 is calculated as: * 1 + 2 + 3 + 4 + 5 = 15, * then 1 + 5 = 6, so the generic root is 6. * <p> * Reference: * https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/ */ public final class GenericRoot { private static final int BASE = 10; private GenericRoot() { } /** * Computes the sum of the digits of a non-negative integer in base 10. * * @param n non-negative integer * @return sum of digits of {@code n} */ private static int sumOfDigits(final int n) { assert n >= 0; if (n < BASE) { return n; } return (n % BASE) + sumOfDigits(n / BASE); } /** * Computes the generic root (repeated digital sum) of an integer. * For negative inputs, the absolute value is used. * * @param n integer input * @return generic root of {@code n} */ public static int genericRoot(final int n) { int number = Math.abs(n); if (number < BASE) { return number; } return genericRoot(sumOfDigits(number)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AliquotSum.java
src/main/java/com/thealgorithms/maths/AliquotSum.java
package com.thealgorithms.maths; import java.util.stream.IntStream; /** * In number theory, the aliquot sum s(n) of a positive integer n is the sum of * all proper divisors of n, that is, all divisors of n other than n itself. For * example, the proper divisors of 15 (that is, the positive divisors of 15 that * are not equal to 15) are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + * 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum */ public final class AliquotSum { private AliquotSum() { } /** * Finds the aliquot sum of an integer number. * * @param number a positive integer * @return aliquot sum of given {@code number} */ public static int getAliquotValue(int number) { var sumWrapper = new Object() { int value = 0; }; IntStream.iterate(1, i -> ++i).limit(number / 2).filter(i -> number % i == 0).forEach(i -> sumWrapper.value += i); return sumWrapper.value; } /** * Function to calculate the aliquot sum of an integer number * * @param n a positive integer * @return aliquot sum of given {@code number} */ public static int getAliquotSum(int n) { if (n <= 0) { return -1; } int sum = 1; double root = Math.sqrt(n); /* * We can get the factors after the root by dividing number by its factors * before the root. * Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100. * Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5. * Now by dividing 100 by each factor before 10 we get: * 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20 * So we get 100, 50, 25 and 20 which are factors of 100 after 10 */ for (int i = 2; i <= root; i++) { if (n % i == 0) { sum += i + n / i; } } // if n is a perfect square then its root was added twice in above loop, so subtracting root // from sum if (root == (int) root) { sum -= (int) root; } return sum; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LuckyNumber.java
src/main/java/com/thealgorithms/maths/LuckyNumber.java
package com.thealgorithms.maths; /** * In number theory, a lucky number is a natural number in a set which is generated by a certain "sieve". * This sieve is similar to the sieve of Eratosthenes that generates the primes, * but it eliminates numbers based on their position in the remaining set, * instead of their value (or position in the initial set of natural numbers). * * Wiki: https://en.wikipedia.org/wiki/Lucky_number */ public final class LuckyNumber { private LuckyNumber() { } // Common validation method private static void validatePositiveNumber(int number) { if (number <= 0) { throw new IllegalArgumentException("Number must be positive."); } } // Function to check recursively for Lucky Number private static boolean isLuckyRecursiveApproach(int n, int counter) { // Base case: If counter exceeds n, number is lucky if (counter > n) { return true; } // If number is eliminated in this step, it's not lucky if (n % counter == 0) { return false; } // Calculate new position after removing every counter-th number int newNumber = n - (n / counter); // Recursive call for next round return isLuckyRecursiveApproach(newNumber, counter + 1); } /** * Check if {@code number} is a Lucky number or not using recursive approach * * @param number the number * @return {@code true} if {@code number} is a Lucky number, otherwise false */ public static boolean isLuckyNumber(int number) { validatePositiveNumber(number); int counterStarting = 2; return isLuckyRecursiveApproach(number, counterStarting); } /** * Check if {@code number} is a Lucky number or not using iterative approach * * @param number the number * @return {@code true} if {@code number} is a Lucky number, otherwise false */ public static boolean isLucky(int number) { validatePositiveNumber(number); int counter = 2; // Position starts from 2 (since first elimination happens at 2) int position = number; // The position of the number in the sequence while (counter <= position) { if (position % counter == 0) { return false; } // Number is eliminated // Update the position of n after removing every counter-th number position = position - (position / counter); counter++; } return true; // Survives all eliminations → Lucky Number } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FindMinRecursion.java
src/main/java/com/thealgorithms/maths/FindMinRecursion.java
package com.thealgorithms.maths; public final class FindMinRecursion { private FindMinRecursion() { } /** * Get min of an array using divide and conquer algorithm * * @param array contains elements * @param low the index of the first element * @param high the index of the last element * @return min of {@code array} */ public static int min(final int[] array, final int low, final int high) { if (array.length == 0) { throw new IllegalArgumentException("array must be non-empty."); } if (low == high) { return array[low]; // or array[high] } int mid = (low + high) >>> 1; int leftMin = min(array, low, mid); // get min in [low, mid] int rightMin = min(array, mid + 1, high); // get min in [mid+1, high] return Math.min(leftMin, rightMin); } /** * Get min of an array using recursion algorithm * * @param array contains elements * @return min value of {@code array} */ public static int min(final int[] array) { return min(array, 0, array.length - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java
src/main/java/com/thealgorithms/maths/PowerUsingRecursion.java
package com.thealgorithms.maths; /** * calculate Power using Recursion * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public final class PowerUsingRecursion { private PowerUsingRecursion() { } public static double power(double base, int exponent) { // Base case: anything raised to the power of 0 is 1 if (exponent == 0) { return 1; } // Recursive case: base ^ exponent = base * base ^ (exponent - 1) // Recurse with a smaller exponent and multiply with base return base * power(base, exponent - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PerfectCube.java
src/main/java/com/thealgorithms/maths/PerfectCube.java
package com.thealgorithms.maths; /** * https://en.wikipedia.org/wiki/Cube_(algebra) */ public final class PerfectCube { private PerfectCube() { } /** * Check if a number is perfect cube or not * * @param number number to check * @return {@code true} if {@code number} is perfect cube, otherwise * {@code false} */ public static boolean isPerfectCube(int number) { number = Math.abs(number); // converting negative number to positive number int a = (int) Math.pow(number, 1.0 / 3); return a * a * a == number; } /** * Check if a number is perfect cube or not by using Math.cbrt function * * @param number number to check * @return {@code true} if {@code number} is perfect cube, otherwise * {@code false} */ public static boolean isPerfectCubeMathCbrt(int number) { double cubeRoot = Math.cbrt(number); return cubeRoot == (int) cubeRoot; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PascalTriangle.java
src/main/java/com/thealgorithms/maths/PascalTriangle.java
package com.thealgorithms.maths; public final class PascalTriangle { private PascalTriangle() { } /** *In mathematics, Pascal's triangle is a triangular array of the binomial coefficients that *arises in probability theory, combinatorics, and algebra. In much of the Western world, it is *named after the French mathematician Blaise Pascal, although other mathematicians studied it *centuries before him in India, Persia, China, Germany, and Italy. * * The rows of Pascal's triangle are conventionally enumerated starting with row n=0 at the top *(the 0th row). The entries in each row are numbered from the left beginning with k=0 and are *usually staggered relative to the numbers in the adjacent rows. The triangle may be *constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero *entry 1. Each entry of each subsequent row is constructed by adding the number above and to *the left with the number above and to the right, treating blank entries as 0. For example, the *initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers *1 and 3 in the third row are added to produce the number 4 in the fourth row. * * *<p> * link:-https://en.wikipedia.org/wiki/Pascal%27s_triangle * * <p> * Example:- * 1 * 1 1 * 1 2 1 * 1 3 3 1 * 1 4 6 4 1 * 1 5 10 10 5 1 * 1 6 15 20 15 6 1 * 1 7 21 35 35 21 7 1 * 1 8 28 56 70 56 28 8 1 * */ public static int[][] pascal(int n) { /* * @param arr An auxiliary array to store generated pascal triangle values * @return */ int[][] arr = new int[n][n]; /* * @param line Iterate through every line and print integer(s) in it * @param i Represents the column number of the element we are currently on */ for (int line = 0; line < n; line++) { /* * @Every line has number of integers equal to line number */ for (int i = 0; i <= line; i++) { // First and last values in every row are 1 if (line == i || i == 0) { arr[line][i] = 1; } else { arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i]; } } } return arr; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
src/main/java/com/thealgorithms/maths/VectorCrossProduct.java
package com.thealgorithms.maths; /** * @file * * @brief Calculates the [Cross * Product](https://en.wikipedia.org/wiki/Cross_product) and the magnitude of * two mathematical 3D vectors. * * * @details Cross Product of two vectors gives a vector. Direction Ratios of a * vector are the numeric parts of the given vector. They are the tree parts of * the vector which determine the magnitude (value) of the vector. The method of * finding a cross product is the same as finding the determinant of an order 3 * matrix consisting of the first row with unit vectors of magnitude 1, the * second row with the direction ratios of the first vector and the third row * with the direction ratios of the second vector. The magnitude of a vector is * it's value expressed as a number. Let the direction ratios of the first * vector, P be: a, b, c Let the direction ratios of the second vector, Q be: x, * y, z Therefore the calculation for the cross product can be arranged as: * * ``` P x Q: 1 1 1 a b c x y z ``` * * The direction ratios (DR) are calculated as follows: 1st DR, J: (b * z) - (c * * y) 2nd DR, A: -((a * z) - (c * x)) 3rd DR, N: (a * y) - (b * x) * * Therefore, the direction ratios of the cross product are: J, A, N The * following Java Program calculates the direction ratios of the cross products * of two vector. The program uses a function, cross() for doing so. The * direction ratios for the first and the second vector has to be passed one by * one separated by a space character. * * Magnitude of a vector is the square root of the sum of the squares of the * direction ratios. * * * For maintaining filename consistency, Vector class has been termed as * VectorCrossProduct * * @author [Syed](https://github.com/roeticvampire) */ public class VectorCrossProduct { int x; int y; int z; // Default constructor, initialises all three Direction Ratios to 0 VectorCrossProduct() { x = 0; y = 0; z = 0; } /** * constructor, initialises Vector with given Direction Ratios * * @param vectorX set to x * @param vectorY set to y * @param vectorZ set to z */ VectorCrossProduct(int vectorX, int vectorY, int vectorZ) { x = vectorX; y = vectorY; z = vectorZ; } /** * Returns the magnitude of the vector * * @return double */ double magnitude() { return Math.sqrt(x * x + y * y + z * z); } /** * Returns the dot product of the current vector with a given vector * * @param b: the second vector * @return int: the dot product */ int dotProduct(VectorCrossProduct b) { return x * b.x + y * b.y + z * b.z; } /** * Returns the cross product of the current vector with a given vector * * @param b: the second vector * @return vectorCrossProduct: the cross product */ VectorCrossProduct crossProduct(VectorCrossProduct b) { VectorCrossProduct product = new VectorCrossProduct(); product.x = (y * b.z) - (z * b.y); product.y = -((x * b.z) - (z * b.x)); product.z = (x * b.y) - (y * b.x); return product; } /** * Display the Vector */ void displayVector() { System.out.println("x : " + x + "\ty : " + y + "\tz : " + z); } public static void main(String[] args) { test(); } static void test() { // Create two vectors VectorCrossProduct a = new VectorCrossProduct(1, -2, 3); VectorCrossProduct b = new VectorCrossProduct(2, 0, 3); // Determine cross product VectorCrossProduct crossProd = a.crossProduct(b); crossProd.displayVector(); // Determine dot product int dotProd = a.dotProduct(b); System.out.println("Dot Product of a and b: " + dotProd); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java
src/main/java/com/thealgorithms/maths/SieveOfEratosthenes.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; /** * Sieve of Eratosthenes Algorithm * An efficient algorithm to find all prime numbers up to a given limit. * * Algorithm: * 1. Create a boolean array of size n+1, initially all true * 2. Mark 0 and 1 as not prime * 3. For each number i from 2 to sqrt(n): * - If i is still marked as prime * - Mark all multiples of i (starting from i²) as not prime * 4. Collect all numbers still marked as prime * * Time Complexity: O(n log log n) * Space Complexity: O(n) * * @author Navadeep0007 * @see <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a> */ public final class SieveOfEratosthenes { private SieveOfEratosthenes() { // Utility class, prevent instantiation } /** * Finds all prime numbers up to n using the Sieve of Eratosthenes algorithm * * @param n the upper limit (inclusive) * @return a list of all prime numbers from 2 to n * @throws IllegalArgumentException if n is negative */ public static List<Integer> findPrimes(int n) { if (n < 0) { throw new IllegalArgumentException("Input must be non-negative"); } if (n < 2) { return new ArrayList<>(); } // Create boolean array, initially all true boolean[] isPrime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { isPrime[i] = true; } // Sieve process for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { // Mark all multiples of i as not prime for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } } // Collect all prime numbers List<Integer> primes = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (isPrime[i]) { primes.add(i); } } return primes; } /** * Counts the number of prime numbers up to n * * @param n the upper limit (inclusive) * @return count of prime numbers from 2 to n */ public static int countPrimes(int n) { return findPrimes(n).size(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ReverseNumber.java
src/main/java/com/thealgorithms/maths/ReverseNumber.java
package com.thealgorithms.maths; /** * @brief utility class reversing numbers */ public final class ReverseNumber { private ReverseNumber() { } /** * @brief reverses the input number * @param number the input number * @exception IllegalArgumentException number is negative * @return the number created by reversing the order of digits of the input number */ public static int reverseNumber(int number) { if (number < 0) { throw new IllegalArgumentException("number must be nonnegative."); } int result = 0; while (number > 0) { result *= 10; result += number % 10; number /= 10; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FFT.java
src/main/java/com/thealgorithms/maths/FFT.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * Class for calculating the Fast Fourier Transform (FFT) of a discrete signal * using the Cooley-Tukey algorithm. * * @author Ioannis Karavitsis * @version 1.0 */ public final class FFT { private FFT() { } /** * This class represents a complex number and has methods for basic * operations. * * <p> * More info: * https://introcs.cs.princeton.edu/java/32class/Complex.java.html */ static class Complex { private double real; private double img; /** * Default Constructor. Creates the complex number 0. */ Complex() { real = 0; img = 0; } /** * Constructor. Creates a complex number. * * @param r The real part of the number. * @param i The imaginary part of the number. */ Complex(double r, double i) { real = r; img = i; } /** * Returns the real part of the complex number. * * @return The real part of the complex number. */ public double getReal() { return real; } /** * Returns the imaginary part of the complex number. * * @return The imaginary part of the complex number. */ public double getImaginary() { return img; } /** * Adds this complex number to another. * * @param z The number to be added. * @return The sum. */ public Complex add(Complex z) { Complex temp = new Complex(); temp.real = this.real + z.real; temp.img = this.img + z.img; return temp; } /** * Subtracts a number from this complex number. * * @param z The number to be subtracted. * @return The difference. */ public Complex subtract(Complex z) { Complex temp = new Complex(); temp.real = this.real - z.real; temp.img = this.img - z.img; return temp; } /** * Multiplies this complex number by another. * * @param z The number to be multiplied. * @return The product. */ public Complex multiply(Complex z) { Complex temp = new Complex(); temp.real = this.real * z.real - this.img * z.img; temp.img = this.real * z.img + this.img * z.real; return temp; } /** * Multiplies this complex number by a scalar. * * @param n The real number to be multiplied. * @return The product. */ public Complex multiply(double n) { Complex temp = new Complex(); temp.real = this.real * n; temp.img = this.img * n; return temp; } /** * Finds the conjugate of this complex number. * * @return The conjugate. */ public Complex conjugate() { Complex temp = new Complex(); temp.real = this.real; temp.img = -this.img; return temp; } /** * Finds the magnitude of the complex number. * * @return The magnitude. */ public double abs() { return Math.hypot(this.real, this.img); } /** * Divides this complex number by another. * * @param z The divisor. * @return The quotient. */ public Complex divide(Complex z) { Complex temp = new Complex(); double d = z.abs() * z.abs(); d = (double) Math.round(d * 1000000000d) / 1000000000d; temp.real = (this.real * z.real + this.img * z.img) / (d); temp.img = (this.img * z.real - this.real * z.img) / (d); return temp; } /** * Divides this complex number by a scalar. * * @param n The divisor which is a real number. * @return The quotient. */ public Complex divide(double n) { Complex temp = new Complex(); temp.real = this.real / n; temp.img = this.img / n; return temp; } public double real() { return real; } public double imaginary() { return img; } } /** * Iterative In-Place Radix-2 Cooley-Tukey Fast Fourier Transform Algorithm * with Bit-Reversal. The size of the input signal must be a power of 2. If * it isn't then it is padded with zeros and the output FFT will be bigger * than the input signal. * * <p> * More info: * https://www.algorithm-archive.org/contents/cooley_tukey/cooley_tukey.html * https://www.geeksforgeeks.org/iterative-fast-fourier-transformation-polynomial-multiplication/ * https://en.wikipedia.org/wiki/Cooley%E2%80%93Tukey_FFT_algorithm * https://cp-algorithms.com/algebra/fft.html * @param x The discrete signal which is then converted to the FFT or the * IFFT of signal x. * @param inverse True if you want to find the inverse FFT. * @return */ public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) { /* Pad the signal with zeros if necessary */ paddingPowerOfTwo(x); int n = x.size(); int log2n = findLog2(n); x = fftBitReversal(n, log2n, x); int direction = inverse ? -1 : 1; /* Main loop of the algorithm */ for (int len = 2; len <= n; len *= 2) { double angle = -2 * Math.PI / len * direction; Complex wlen = new Complex(Math.cos(angle), Math.sin(angle)); for (int i = 0; i < n; i += len) { Complex w = new Complex(1, 0); for (int j = 0; j < len / 2; j++) { Complex u = x.get(i + j); Complex v = w.multiply(x.get(i + j + len / 2)); x.set(i + j, u.add(v)); x.set(i + j + len / 2, u.subtract(v)); w = w.multiply(wlen); } } } x = inverseFFT(n, inverse, x); return x; } /* Find the log2(n) */ public static int findLog2(int n) { int log2n = 0; while ((1 << log2n) < n) { log2n++; } return log2n; } /* Swap the values of the signal with bit-reversal method */ public static ArrayList<Complex> fftBitReversal(int n, int log2n, ArrayList<Complex> x) { int reverse; for (int i = 0; i < n; i++) { reverse = reverseBits(i, log2n); if (i < reverse) { Collections.swap(x, i, reverse); } } return x; } /* Divide by n if we want the inverse FFT */ public static ArrayList<Complex> inverseFFT(int n, boolean inverse, ArrayList<Complex> x) { if (inverse) { for (int i = 0; i < x.size(); i++) { Complex z = x.get(i); x.set(i, z.divide(n)); } } return x; } /** * This function reverses the bits of a number. It is used in Cooley-Tukey * FFT algorithm. * * <p> * E.g. num = 13 = 00001101 in binary log2n = 8 Then reversed = 176 = * 10110000 in binary * * <p> * More info: https://cp-algorithms.com/algebra/fft.html * https://www.geeksforgeeks.org/write-an-efficient-c-program-to-reverse-bits-of-a-number/ * * @param num The integer you want to reverse its bits. * @param log2n The number of bits you want to reverse. * @return The reversed number */ private static int reverseBits(int num, int log2n) { int reversed = 0; for (int i = 0; i < log2n; i++) { if ((num & (1 << i)) != 0) { reversed |= 1 << (log2n - 1 - i); } } return reversed; } /** * This method pads an ArrayList with zeros in order to have a size equal to * the next power of two of the previous size. * * @param x The ArrayList to be padded. */ private static void paddingPowerOfTwo(Collection<Complex> x) { int n = 1; int oldSize = x.size(); while (n < oldSize) { n *= 2; } for (int i = 0; i < n - oldSize; i++) { x.add(new Complex()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PowerOfFour.java
src/main/java/com/thealgorithms/maths/PowerOfFour.java
package com.thealgorithms.maths; /** * Utility class for checking if a number is a power of four. * A power of four is a number that can be expressed as 4^n where n is a non-negative integer. * This class provides a method to determine if a given integer is a power of four using bit manipulation. * * @author krishna-medapati (https://github.com/krishna-medapati) */ public final class PowerOfFour { private PowerOfFour() { } /** * Checks if the given integer is a power of four. * * A number is considered a power of four if: * 1. It is greater than zero * 2. It has exactly one '1' bit in its binary representation (power of two) * 3. The '1' bit is at an even position (0, 2, 4, 6, ...) * * The method uses the mask 0x55555555 (binary: 01010101010101010101010101010101) * to check if the set bit is at an even position. * * @param number the integer to check * @return true if the number is a power of four, false otherwise */ public static boolean isPowerOfFour(int number) { if (number <= 0) { return false; } boolean isPowerOfTwo = (number & (number - 1)) == 0; boolean hasEvenBitPosition = (number & 0x55555555) != 0; return isPowerOfTwo && hasEvenBitPosition; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PollardRho.java
src/main/java/com/thealgorithms/maths/PollardRho.java
package com.thealgorithms.maths; /* * Java program for pollard rho algorithm * The algorithm is used to factorize a number n = pq, * where p is a non-trivial factor. * Pollard's rho algorithm is an algorithm for integer factorization * and it takes as its inputs n, the integer to be factored; * and g(x), a polynomial in x computed modulo n. * In the original algorithm, g(x) = ((x ^ 2) − 1) mod n, * but nowadays it is more common to use g(x) = ((x ^ 2) + 1 ) mod n. * The output is either a non-trivial factor of n, or failure. * It performs the following steps: * x ← 2 * y ← 2 * d ← 1 * while d = 1: * x ← g(x) * y ← g(g(y)) * d ← gcd(|x - y|, n) * if d = n: * return failure * else: * return d * Here x and y corresponds to xi and xj in the previous section. * Note that this algorithm may fail to find a nontrivial factor even when n is composite. * In that case, the method can be tried again, using a starting value other than 2 or a different g(x) * * Wikipedia: https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class PollardRho { private PollardRho() { } /** * This method returns a polynomial in x computed modulo n * * @param base Integer base of the polynomial * @param modulus Integer is value which is to be used to perform modulo operation over the * polynomial * @return Integer (((base * base) - 1) % modulus) */ static int g(int base, int modulus) { return ((base * base) - 1) % modulus; } /** * This method returns a non-trivial factor of given integer number * * @param number Integer is a integer value whose non-trivial factor is to be found * @return Integer non-trivial factor of number * @throws RuntimeException object if GCD of given number cannot be found */ static int pollardRho(int number) { int x = 2; int y = 2; int d = 1; while (d == 1) { // tortoise move x = g(x, number); // hare move y = g(g(y, number), number); // check GCD of |x-y| and number d = GCD.gcd(Math.abs(x - y), number); } if (d == number) { throw new RuntimeException("GCD cannot be found."); } return d; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FindMaxRecursion.java
src/main/java/com/thealgorithms/maths/FindMaxRecursion.java
package com.thealgorithms.maths; public final class FindMaxRecursion { private FindMaxRecursion() { } /** * Get max of an array using divide and conquer algorithm * * @param array contains elements * @param low the index of the first element * @param high the index of the last element * @return max of {@code array} */ public static int max(final int[] array, final int low, final int high) { if (array.length == 0) { throw new IllegalArgumentException("Array must be non-empty."); } if (low == high) { return array[low]; // or array[high] } int mid = (low + high) >>> 1; int leftMax = max(array, low, mid); // get max in [low, mid] int rightMax = max(array, mid + 1, high); // get max in [mid+1, high] return Math.max(leftMax, rightMax); } /** * Get max of an array using recursion algorithm * * @param array contains elements * @return max value of {@code array} */ public static int max(final int[] array) { return max(array, 0, array.length - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SmithNumber.java
src/main/java/com/thealgorithms/maths/SmithNumber.java
package com.thealgorithms.maths; import com.thealgorithms.maths.Prime.PrimeCheck; /** * In number theory, a smith number is a composite number for which, in a given number base, * the sum of its digits is equal to the sum of the digits in its prime factorization in the same base. * * For example, in base 10, 378 = 21 X 33 X 71 is a Smith number since 3 + 7 + 8 = 2 X 1 + 3 X 3 + 7 X 1, * and 22 = 21 X 111 is a Smith number, because 2 + 2 = 2 X 1 + (1 + 1) X 1. * * Wiki: https://en.wikipedia.org/wiki/Smith_number */ public final class SmithNumber { private SmithNumber() { } private static int primeFactorDigitSum(int n) { int sum = 0; int num = n; // Factorize the number using trial division for (int i = 2; i * i <= num; i++) { while (n % i == 0) { // while i divides n sum += SumOfDigits.sumOfDigits(i); // add sum of digits of factor n /= i; // divide n by the factor } } // If n is still > 1, it itself is a prime factor if (n > 1) { sum += SumOfDigits.sumOfDigits(n); } return sum; } /** * Check if {@code number} is Smith number or not * * @param number the number * @return {@code true} if {@code number} is a Smith number, otherwise false */ public static boolean isSmithNumber(int number) { if (PrimeCheck.isPrime(number)) { return false; // Smith numbers must be composite } return SumOfDigits.sumOfDigits(number) == primeFactorDigitSum(number); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Convolution.java
src/main/java/com/thealgorithms/maths/Convolution.java
package com.thealgorithms.maths; /** * Class for linear convolution of two discrete signals * * @author Ioannis Karavitsis * @version 1.0 */ public final class Convolution { private Convolution() { } /** * Discrete linear convolution function. Both input signals and the output * signal must start from 0. If you have a signal that has values before 0 * then shift it to start from 0. * * @param a The first discrete signal * @param b The second discrete signal * @return The convolved signal */ public static double[] convolution(double[] a, double[] b) { double[] convolved = new double[a.length + b.length - 1]; /* * Discrete convolution formula: * C[i] = Σ A[k] * B[i - k] * where k ranges over valid indices so that both A[k] and B[i-k] are in bounds. */ for (int i = 0; i < convolved.length; i++) { double sum = 0; int kStart = Math.max(0, i - b.length + 1); int kEnd = Math.min(i, a.length - 1); for (int k = kStart; k <= kEnd; k++) { sum += a[k] * b[i - k]; } convolved[i] = sum; } return convolved; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
package com.thealgorithms.maths; /* * Java program for Binomial Coefficients * Binomial Coefficients: A binomial coefficient C(n,k) gives number ways * in which k objects can be chosen from n objects. * Wikipedia: https://en.wikipedia.org/wiki/Binomial_coefficient * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class BinomialCoefficient { private BinomialCoefficient() { } /** * This method returns the number of ways in which k objects can be chosen from n objects * * @param totalObjects Total number of objects * @param numberOfObjects Number of objects to be chosen from total_objects * @return number of ways in which no_of_objects objects can be chosen from total_objects * objects */ public static int binomialCoefficient(int totalObjects, int numberOfObjects) { // Base Case if (numberOfObjects > totalObjects) { return 0; } // Base Case if (numberOfObjects == 0 || numberOfObjects == totalObjects) { return 1; } // Recursive Call return (binomialCoefficient(totalObjects - 1, numberOfObjects - 1) + binomialCoefficient(totalObjects - 1, numberOfObjects)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/KaprekarNumbers.java
src/main/java/com/thealgorithms/maths/KaprekarNumbers.java
package com.thealgorithms.maths; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; /** * Utility class for identifying and working with Kaprekar Numbers. * <p> * A Kaprekar number is a positive integer with the following property: * If you square it, then split the resulting number into two parts (right part * has same number of * digits as the original number, left part has the remaining digits), and * finally add the two * parts together, you get the original number. * <p> * For example: * <ul> * <li>9: 9² = 81 → 8 + 1 = 9 (Kaprekar number)</li> * <li>45: 45² = 2025 → 20 + 25 = 45 (Kaprekar number)</li> * <li>297: 297² = 88209 → 88 + 209 = 297 (Kaprekar number)</li> * </ul> * <p> * Note: The right part can have leading zeros, but must not be all zeros. * * @see <a href="https://en.wikipedia.org/wiki/Kaprekar_number">Kaprekar Number * - Wikipedia</a> * @author TheAlgorithms (https://github.com/TheAlgorithms) */ public final class KaprekarNumbers { private KaprekarNumbers() { } /** * Finds all Kaprekar numbers within a given range (inclusive). * * @param start the starting number of the range (inclusive) * @param end the ending number of the range (inclusive) * @return a list of all Kaprekar numbers in the specified range * @throws IllegalArgumentException if start is greater than end or if start is * negative */ public static List<Long> kaprekarNumberInRange(long start, long end) { if (start > end) { throw new IllegalArgumentException("Start must be less than or equal to end. Given start: " + start + ", end: " + end); } if (start < 0) { throw new IllegalArgumentException("Start must be non-negative. Given start: " + start); } ArrayList<Long> list = new ArrayList<>(); for (long i = start; i <= end; i++) { if (isKaprekarNumber(i)) { list.add(i); } } return list; } /** * Checks whether a given number is a Kaprekar number. * <p> * The algorithm works as follows: * <ol> * <li>Square the number</li> * <li>Split the squared number into two parts: left and right</li> * <li>The right part has the same number of digits as the original number</li> * <li>Add the left and right parts</li> * <li>If the sum equals the original number, it's a Kaprekar number</li> * </ol> * <p> * Special handling is required for numbers whose squares contain zeros. * * @param num the number to check * @return true if the number is a Kaprekar number, false otherwise * @throws IllegalArgumentException if num is negative */ public static boolean isKaprekarNumber(long num) { if (num < 0) { throw new IllegalArgumentException("Number must be non-negative. Given: " + num); } if (num == 0 || num == 1) { return true; } String number = Long.toString(num); BigInteger originalNumber = BigInteger.valueOf(num); BigInteger numberSquared = originalNumber.multiply(originalNumber); String squaredStr = numberSquared.toString(); // Special case: if the squared number has the same length as the original if (number.length() == squaredStr.length()) { return number.equals(squaredStr); } // Calculate the split position int splitPos = squaredStr.length() - number.length(); // Split the squared number into left and right parts String leftPart = squaredStr.substring(0, splitPos); String rightPart = squaredStr.substring(splitPos); // Parse the parts as BigInteger (handles empty left part as zero) BigInteger leftNum = leftPart.isEmpty() ? BigInteger.ZERO : new BigInteger(leftPart); BigInteger rightNum = new BigInteger(rightPart); // Check if right part is all zeros (invalid for Kaprekar numbers except 1) if (rightNum.equals(BigInteger.ZERO)) { return false; } // Check if the sum equals the original number return leftNum.add(rightNum).equals(originalNumber); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/DistanceFormula.java
src/main/java/com/thealgorithms/maths/DistanceFormula.java
package com.thealgorithms.maths; public final class DistanceFormula { private DistanceFormula() { } public static double euclideanDistance(double x1, double y1, double x2, double y2) { double dX = Math.pow(x2 - x1, 2); double dY = Math.pow(y2 - x1, 2); return Math.sqrt(dX + dY); } public static double manhattanDistance(double x1, double y1, double x2, double y2) { return Math.abs(x1 - x2) + Math.abs(y1 - y2); } public static int hammingDistance(int[] b1, int[] b2) { int d = 0; if (b1.length != b2.length) { return -1; // error, both arrays must have the same length } for (int i = 0; i < b1.length; i++) { d += Math.abs(b1[i] - b2[i]); } return d; } public static double minkowskiDistance(double[] p1, double[] p2, int p) { double d = 0; double distance = 0.0; if (p1.length != p2.length) { return -1; // error, both arrays must have the same length } for (int i = 0; i < p1.length; i++) { distance += Math.abs(Math.pow(p1[i] - p2[i], p)); } distance = Math.pow(distance, (double) 1 / p); d = distance; return d; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
src/main/java/com/thealgorithms/maths/AutomorphicNumber.java
package com.thealgorithms.maths; import java.math.BigInteger; /** * <a href="https://en.wikipedia.org/wiki/Automorphic_number">Automorphic Number</a> * A number is said to be an Automorphic, if it is present in the last digit(s) * of its square. Example- Let the number be 25, its square is 625. Since, * 25(The input number) is present in the last two digits of its square(625), it * is an Automorphic Number. */ public final class AutomorphicNumber { private AutomorphicNumber() { } /** * A function to check if a number is Automorphic number or not * * @param n The number to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise * {@code false} */ public static boolean isAutomorphic(long n) { if (n < 0) { return false; } long square = n * n; // Calculating square of the number long t = n; long numberOfdigits = 0; while (t > 0) { numberOfdigits++; // Calculating number of digits in n t /= 10; } long lastDigits = square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square return n == lastDigits; } /** * A function to check if a number is Automorphic number or not by using String functions * * @param n The number to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise * {@code false} */ public static boolean isAutomorphic2(long n) { if (n < 0) { return false; } long square = n * n; // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } /** * A function to check if a number is Automorphic number or not by using BigInteger * * @param s The number in String to be checked * @return {@code true} if {@code a} is Automorphic number, otherwise * {@code false} */ public static boolean isAutomorphic3(String s) { BigInteger n = new BigInteger(s); if (n.signum() == -1) { return false; // if number is negative, return false } BigInteger square = n.multiply(n); // Calculating square of the number return String.valueOf(square).endsWith(String.valueOf(n)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/DudeneyNumber.java
src/main/java/com/thealgorithms/maths/DudeneyNumber.java
package com.thealgorithms.maths; /** * A number is said to be Dudeney if the sum of the digits, is the cube root of the entered number. * Example- Let the number be 512, its sum of digits is 5+1+2=8. The cube root of 512 is also 8. * Since, the sum of the digits is equal to the cube root of the entered number; * it is a Dudeney Number. */ public final class DudeneyNumber { private DudeneyNumber() { } // returns True if the number is a Dudeney number and False if it is not a Dudeney number. public static boolean isDudeney(final int n) { if (n <= 0) { throw new IllegalArgumentException("Input must me positive."); } // Calculating Cube Root final int cubeRoot = (int) Math.round(Math.pow(n, 1.0 / 3.0)); // If the number is not a perfect cube the method returns false. if (cubeRoot * cubeRoot * cubeRoot != n) { return false; } // If the cube root of the number is not equal to the sum of its digits, we return false. return cubeRoot == SumOfDigits.sumOfDigits(n); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/EvilNumber.java
src/main/java/com/thealgorithms/maths/EvilNumber.java
package com.thealgorithms.maths; /** * In number theory, an evil number is a non-negative integer that has an even number of 1s in its binary expansion. * Non-negative integers that are not evil are called odious numbers. * * Evil Number Wiki: https://en.wikipedia.org/wiki/Evil_number * Odious Number Wiki: https://en.wikipedia.org/wiki/Odious_number */ public final class EvilNumber { private EvilNumber() { } // Function to count number of one bits in a number using bitwise operators private static int countOneBits(int number) { int oneBitCounter = 0; while (number > 0) { oneBitCounter += number & 1; // increment count if last bit is 1 number >>= 1; // right shift to next bit } return oneBitCounter; } /** * Check either {@code number} is an Evil number or Odious number * * @param number the number * @return {@code true} if {@code number} is an Evil number, otherwise false (in case of of Odious number) */ public static boolean isEvilNumber(int number) { if (number < 0) { throw new IllegalArgumentException("Negative numbers are not allowed."); } int noOfOneBits = countOneBits(number); return noOfOneBits % 2 == 0; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/DigitalRoot.java
src/main/java/com/thealgorithms/maths/DigitalRoot.java
package com.thealgorithms.maths; /** * @author <a href="https://github.com/skmodi649">Suraj Kumar Modi</a> * You are given a number n. You need to find the digital root of n. * DigitalRoot of a number is the recursive sum of its digits until we get a single digit number. * * Test Case 1: * Input: * n = 1 * Output: 1 * Explanation: Digital root of 1 is 1 * * Test Case 2: * Input: * n = 99999 * Output: 9 * Explanation: Sum of digits of 99999 is 45 * which is not a single digit number, hence * sum of digit of 45 is 9 which is a single * digit number. * Algorithm : * Step 1 : Define a method digitalRoot(int n) * Step 2 : Define another method single(int n) * Step 3 : digitalRoot(int n) method takes output of single(int n) as input * if(single(int n) <= 9) * return single(n) * else * return digitalRoot(single(n)) * Step 4 : single(int n) calculates the sum of digits of number n recursively * if(n<=9) * return n; * else * return (n%10) + (n/10) * Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and * print the result */ final class DigitalRoot { private DigitalRoot() { } public static int digitalRoot(int n) { if (single(n) <= 9) { // If n is already single digit than simply call single method and // return the value return single(n); } else { return digitalRoot(single(n)); } } /** * Time Complexity: O((Number of Digits)^2) Auxiliary Space Complexity: * O(Number of Digits) Constraints: 1 <= n <= 10^7 */ // This function is used for finding the sum of the digits of number public static int single(int n) { if (n <= 9) { // if n becomes less than 10 than return n return n; } else { return (n % 10) + single(n / 10); // n % 10 for extracting digits one by one } } // n / 10 is the number obtained after removing the digit one by one // The Sum of digits is stored in the Stack memory and then finally returned }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/CollatzConjecture.java
src/main/java/com/thealgorithms/maths/CollatzConjecture.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; /** * <a href="https://en.wikipedia.org/wiki/Collatz_conjecture">...</a> */ public class CollatzConjecture { /** * Calculate the next number of the sequence. * * @param n current number of the sequence * @return next number of the sequence */ public int nextNumber(final int n) { if (n % 2 == 0) { return n / 2; } return 3 * n + 1; } /** * Calculate the Collatz sequence of any natural number. * * @param firstNumber starting number of the sequence * @return sequence of the Collatz Conjecture */ public List<Integer> collatzConjecture(int firstNumber) { if (firstNumber < 1) { throw new IllegalArgumentException("Must be a natural number"); } ArrayList<Integer> result = new ArrayList<>(); result.add(firstNumber); while (firstNumber != 1) { result.add(nextNumber(firstNumber)); firstNumber = nextNumber(firstNumber); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/GCD.java
src/main/java/com/thealgorithms/maths/GCD.java
package com.thealgorithms.maths; /** * This class provides methods to compute the Greatest Common Divisor (GCD) of two or more integers. * * The Greatest Common Divisor (GCD) of two or more integers is the largest positive integer that divides each of the integers without leaving a remainder. * * The GCD can be computed using the Euclidean algorithm, which is based on the principle that the GCD of two numbers also divides their difference. * * For more information, refer to the * <a href="https://en.wikipedia.org/wiki/Greatest_common_divisor">Greatest Common Divisor</a> Wikipedia page. * * <b>Example usage:</b> * <pre> * int result1 = GCD.gcd(48, 18); * System.out.println("GCD of 48 and 18: " + result1); // Output: 6 * * int result2 = GCD.gcd(48, 18, 30); * System.out.println("GCD of 48, 18, and 30: " + result2); // Output: 6 * </pre> * @author Oskar Enmalm 3/10/17 */ public final class GCD { private GCD() { } /** * get the greatest common divisor * * @param num1 the first number * @param num2 the second number * @return gcd */ public static int gcd(int num1, int num2) { if (num1 < 0 || num2 < 0) { throw new ArithmeticException(); } if (num1 == 0 || num2 == 0) { return Math.abs(num1 - num2); } while (num1 % num2 != 0) { int remainder = num1 % num2; num1 = num2; num2 = remainder; } return num2; } /** * @brief computes gcd of an array of numbers * * @param numbers the input array * @return gcd of all of the numbers in the input array */ public static int gcd(int... numbers) { int result = 0; for (final var number : numbers) { result = gcd(result, number); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Median.java
src/main/java/com/thealgorithms/maths/Median.java
package com.thealgorithms.maths; import java.util.Arrays; /** * Utility class for calculating the median of an array of integers. * The median is the middle value in a sorted list of numbers. If the list has * an even number * of elements, the median is the average of the two middle values. * * <p> * Time Complexity: O(n log n) due to sorting * <p> * Space Complexity: O(1) if sorting is done in-place * * @see <a href="https://en.wikipedia.org/wiki/Median">Median (Wikipedia)</a> * @see <a href= * "https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/mean-median-basics/a/mean-median-and-mode-review">Mean, * Median, and Mode Review</a> */ public final class Median { private Median() { } /** * Calculates the median of an array of integers. * The array is sorted internally, so the original order is not preserved. * For arrays with an odd number of elements, returns the middle element. * For arrays with an even number of elements, returns the average of the two * middle elements. * * @param values the array of integers to find the median of (can be unsorted) * @return the median value as a double * @throws IllegalArgumentException if the input array is empty or null */ public static double median(int[] values) { if (values == null || values.length == 0) { throw new IllegalArgumentException("Values array cannot be empty or null"); } Arrays.sort(values); int length = values.length; if (length % 2 == 0) { return (values[length / 2] + values[length / 2 - 1]) / 2.0; } else { return values[length / 2]; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
src/main/java/com/thealgorithms/maths/SimpsonIntegration.java
package com.thealgorithms.maths; import java.util.TreeMap; public class SimpsonIntegration { /* * Calculate definite integrals by using Composite Simpson's rule. * Wiki: https://en.wikipedia.org/wiki/Simpson%27s_rule#Composite_Simpson's_rule * Given f a function and an even number N of intervals that divide the integration interval * e.g. [a, b], we calculate the step h = (b-a)/N and create a table that contains all the x * points of the real axis xi = x0 + i*h and the value f(xi) that corresponds to these xi. * * To evaluate the integral i use the formula below: * I = h/3 * {f(x0) + 4*f(x1) + 2*f(x2) + 4*f(x3) + ... + 2*f(xN-2) + 4*f(xN-1) + f(xN)} * */ public static void main(String[] args) { SimpsonIntegration integration = new SimpsonIntegration(); // Give random data for the example purposes int n = 16; double a = 1; double b = 3; // Check so that n is even if (n % 2 != 0) { System.out.println("n must be even number for Simpsons method. Aborted"); System.exit(1); } // Calculate step h and evaluate the integral double h = (b - a) / (double) n; double integralEvaluation = integration.simpsonsMethod(n, h, a); System.out.println("The integral is equal to: " + integralEvaluation); } /* * @param N: Number of intervals (must be even number N=2*k) * @param h: Step h = (b-a)/N * @param a: Starting point of the interval * @param b: Ending point of the interval * * The interpolation points xi = x0 + i*h are stored the treeMap data * * @return result of the integral evaluation */ public double simpsonsMethod(int n, double h, double a) { TreeMap<Integer, Double> data = new TreeMap<>(); // Key: i, Value: f(xi) double temp; double xi = a; // Initialize the variable xi = x0 + 0*h // Create the table of xi and yi points for (int i = 0; i <= n; i++) { temp = f(xi); // Get the value of the function at that point data.put(i, temp); xi += h; // Increase the xi to the next point } // Apply the formula double integralEvaluation = 0; for (int i = 0; i < data.size(); i++) { if (i == 0 || i == data.size() - 1) { integralEvaluation += data.get(i); System.out.println("Multiply f(x" + i + ") by 1"); } else if (i % 2 != 0) { integralEvaluation += (double) 4 * data.get(i); System.out.println("Multiply f(x" + i + ") by 4"); } else { integralEvaluation += (double) 2 * data.get(i); System.out.println("Multiply f(x" + i + ") by 2"); } } // Multiply by h/3 integralEvaluation = h / 3 * integralEvaluation; // Return the result return integralEvaluation; } // Sample function f // Function f(x) = e^(-x) * (4 - x^2) public double f(double x) { return Math.exp(-x) * (4 - Math.pow(x, 2)); // return Math.sqrt(x); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java
src/main/java/com/thealgorithms/maths/ChineseRemainderTheorem.java
package com.thealgorithms.maths; import java.util.List; /** * @brief Implementation of the Chinese Remainder Theorem (CRT) algorithm * @details * The Chinese Remainder Theorem (CRT) is used to solve systems of * simultaneous congruences. Given several pairwise coprime moduli * and corresponding remainders, the algorithm finds the smallest * positive solution. */ public final class ChineseRemainderTheorem { private ChineseRemainderTheorem() { } /** * @brief Solves the Chinese Remainder Theorem problem. * @param remainders The list of remainders. * @param moduli The list of pairwise coprime moduli. * @return The smallest positive solution that satisfies all the given congruences. */ public static int solveCRT(List<Integer> remainders, List<Integer> moduli) { int product = 1; int result = 0; // Calculate the product of all moduli for (int mod : moduli) { product *= mod; } // Apply the formula for each congruence for (int i = 0; i < moduli.size(); i++) { int partialProduct = product / moduli.get(i); int inverse = modInverse(partialProduct, moduli.get(i)); result += remainders.get(i) * partialProduct * inverse; } // Adjust result to be the smallest positive solution result = result % product; if (result < 0) { result += product; } return result; } /** * @brief Computes the modular inverse of a number with respect to a modulus using * the Extended Euclidean Algorithm. * @param a The number for which to find the inverse. * @param m The modulus. * @return The modular inverse of a modulo m. */ private static int modInverse(int a, int m) { int m0 = m; int x0 = 0; int x1 = 1; if (m == 1) { return 0; } while (a > 1) { int q = a / m; int t = m; // m is remainder now, process same as Euclid's algorithm m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) { x1 += m0; } return x1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java
src/main/java/com/thealgorithms/maths/FibonacciJavaStreams.java
package com.thealgorithms.maths; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import java.util.stream.Stream; /** * @author: caos321 * @date: 14 October 2021 (Thursday) */ public final class FibonacciJavaStreams { private FibonacciJavaStreams() { } public static Optional<BigDecimal> calculate(final BigDecimal index) { if (index == null || index.compareTo(BigDecimal.ZERO) < 0) { throw new IllegalArgumentException("Input index cannot be null or negative!"); } if (index.compareTo(BigDecimal.ONE) < 0) { return Optional.of(BigDecimal.ZERO); } if (index.compareTo(BigDecimal.TWO) < 0) { return Optional.of(BigDecimal.ONE); } final List<BigDecimal> results = Stream.iterate(index, x -> x.compareTo(BigDecimal.ZERO) > 0, x -> x.subtract(BigDecimal.ONE)) .reduce(List.of(), (list, current) -> list.isEmpty() || list.size() < 2 ? List.of(BigDecimal.ZERO, BigDecimal.ONE) : List.of(list.get(1), list.get(0).add(list.get(1))), (list1, list2) -> list1); return results.isEmpty() ? Optional.empty() : Optional.of(results.get(results.size() - 1)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FindMax.java
src/main/java/com/thealgorithms/maths/FindMax.java
package com.thealgorithms.maths; public final class FindMax { private FindMax() { } /** * @brief finds the maximum value stored in the input array * * @param array the input array * @exception IllegalArgumentException input array is empty * @return the maximum value stored in the input array */ public static int findMax(final int[] array) { int n = array.length; if (n == 0) { throw new IllegalArgumentException("Array must be non-empty."); } int max = array[0]; for (int i = 1; i < n; i++) { if (array[i] > max) { max = array[i]; } } return max; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java
src/main/java/com/thealgorithms/maths/KaratsubaMultiplication.java
package com.thealgorithms.maths; import java.math.BigInteger; /** * This class provides an implementation of the Karatsuba multiplication algorithm. * * <p> * Karatsuba multiplication is a divide-and-conquer algorithm for multiplying two large * numbers. It is faster than the classical multiplication algorithm and reduces the * time complexity to O(n^1.585) by breaking the multiplication of two n-digit numbers * into three multiplications of n/2-digit numbers. * </p> * * <p> * The main idea of the Karatsuba algorithm is based on the following observation: * </p> * * <pre> * Let x and y be two numbers: * x = a * 10^m + b * y = c * 10^m + d * * Then, the product of x and y can be expressed as: * x * y = (a * c) * 10^(2*m) + ((a * d) + (b * c)) * 10^m + (b * d) * </pre> * * The Karatsuba algorithm calculates this more efficiently by reducing the number of * multiplications from four to three by using the identity: * * <pre> * (a + b)(c + d) = ac + ad + bc + bd * </pre> * * <p> * The recursion continues until the numbers are small enough to multiply directly using * the traditional method. * </p> */ public final class KaratsubaMultiplication { /** * Private constructor to hide the implicit public constructor */ private KaratsubaMultiplication() { } /** * Multiplies two large numbers using the Karatsuba algorithm. * * <p> * This method recursively splits the numbers into smaller parts until they are * small enough to be multiplied directly using the traditional method. * </p> * * @param x The first large number to be multiplied (BigInteger). * @param y The second large number to be multiplied (BigInteger). * @return The product of the two numbers (BigInteger). */ public static BigInteger karatsuba(BigInteger x, BigInteger y) { // Base case: when numbers are small enough, use direct multiplication // If the number is 4 bits or smaller, switch to the classical method if (x.bitLength() <= 4 || y.bitLength() <= 4) { return x.multiply(y); } // Find the maximum bit length of the two numbers int n = Math.max(x.bitLength(), y.bitLength()); // Split the numbers in the middle int m = n / 2; // High and low parts of the first number x (x = a * 10^m + b) BigInteger high1 = x.shiftRight(m); // a = x / 2^m (higher part) BigInteger low1 = x.subtract(high1.shiftLeft(m)); // b = x - a * 2^m (lower part) // High and low parts of the second number y (y = c * 10^m + d) BigInteger high2 = y.shiftRight(m); // c = y / 2^m (higher part) BigInteger low2 = y.subtract(high2.shiftLeft(m)); // d = y - c * 2^m (lower part) // Recursively calculate three products BigInteger z0 = karatsuba(low1, low2); // z0 = b * d (low1 * low2) BigInteger z1 = karatsuba(low1.add(high1), low2.add(high2)); // z1 = (a + b) * (c + d) BigInteger z2 = karatsuba(high1, high2); // z2 = a * c (high1 * high2) // Combine the results using Karatsuba's formula // z0 + ((z1 - z2 - z0) << m) + (z2 << 2m) return z2 .shiftLeft(2 * m) // z2 * 10^(2*m) .add(z1.subtract(z2).subtract(z0).shiftLeft(m)) // (z1 - z2 - z0) * 10^m .add(z0); // z0 } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PerfectNumber.java
src/main/java/com/thealgorithms/maths/PerfectNumber.java
package com.thealgorithms.maths; /** * In number theory, a perfect number is a positive integer that is equal to the * sum of its positive divisors, excluding the number itself. For instance, 6 * has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a * perfect number. * * link:https://en.wikipedia.org/wiki/Perfect_number */ public final class PerfectNumber { private PerfectNumber() { } /** * Check if {@code number} is perfect number or not * * @param number the number * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber(int number) { if (number <= 0) { return false; } int sum = 0; /* sum of its positive divisors */ for (int i = 1; i < number; ++i) { if (number % i == 0) { sum += i; } } return sum == number; } /** * Check if {@code n} is perfect number or not * * @param n the number * @return {@code true} if {@code number} is perfect number, otherwise false */ public static boolean isPerfectNumber2(int n) { if (n <= 0) { return false; } int sum = 1; double root = Math.sqrt(n); /* * We can get the factors after the root by dividing number by its factors * before the root. * Ex- Factors of 100 are 1, 2, 4, 5, 10, 20, 25, 50 and 100. * Root of 100 is 10. So factors before 10 are 1, 2, 4 and 5. * Now by dividing 100 by each factor before 10 we get: * 100/1 = 100, 100/2 = 50, 100/4 = 25 and 100/5 = 20 * So we get 100, 50, 25 and 20 which are factors of 100 after 10 */ for (int i = 2; i <= root; i++) { if (n % i == 0) { sum += i + n / i; } } // if n is a perfect square then its root was added twice in above loop, so subtracting root // from sum if (root == (int) root) { sum -= (int) root; } return sum == n; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/StandardScore.java
src/main/java/com/thealgorithms/maths/StandardScore.java
package com.thealgorithms.maths; public final class StandardScore { private StandardScore() { } public static double zScore(double num, double mean, double stdDev) { return (num - mean) / stdDev; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PiNilakantha.java
src/main/java/com/thealgorithms/maths/PiNilakantha.java
package com.thealgorithms.maths; public final class PiNilakantha { private PiNilakantha() { } // Calculates Pi using Nilakantha's infinite series // Method 2 in the following link explains the algorithm // https://en.scratch-wiki.info/wiki/Calculating_Pi public static void main(String[] args) { assert calculatePi(0) == 3.0; assert calculatePi(10) > 3.0; assert calculatePi(100) < 4.0; System.out.println(calculatePi(500)); } /** * @param iterations number of times the infinite series gets repeated Pi * get more accurate the higher the value of iterations is Values from 0 up * to 500 are allowed since double precision is not sufficient for more than * about 500 repetitions of this algorithm * @return the pi value of the calculation with a precision of x iteration */ public static double calculatePi(int iterations) { if (iterations < 0 || iterations > 500) { throw new IllegalArgumentException("Please input Integer Number between 0 and 500"); } double pi = 3; int divCounter = 2; for (int i = 0; i < iterations; i++) { if (i % 2 == 0) { pi = pi + 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } else { pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2)); } divCounter += 2; } return pi; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
src/main/java/com/thealgorithms/maths/FastInverseSqrt.java
package com.thealgorithms.maths; /** * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> * Program description - To find out the inverse square root of the given number * <a href="https://en.wikipedia.org/wiki/Fast_inverse_square_root">Wikipedia</a> */ public final class FastInverseSqrt { private FastInverseSqrt() { } /** * Returns the inverse square root of the given number upto 6 - 8 decimal places. * calculates the inverse square root of the given number and returns true if calculated answer * matches with given answer else returns false * * OUTPUT : * Input - number = 4522 * Output: it calculates the inverse squareroot of a number and returns true with it matches the * given answer else returns false. 1st approach Time Complexity : O(1) Auxiliary Space Complexity : * O(1) Input - number = 4522 Output: it calculates the inverse squareroot of a number and returns * true with it matches the given answer else returns false. 2nd approach Time Complexity : O(1) * Auxiliary Space Complexity : O(1) */ public static boolean inverseSqrt(float number) { float x = number; float xhalf = 0.5f * x; int i = Float.floatToIntBits(x); i = 0x5f3759df - (i >> 1); x = Float.intBitsToFloat(i); x = x * (1.5f - xhalf * x * x); return x == ((float) 1 / (float) Math.sqrt(number)); } /** * Returns the inverse square root of the given number upto 14 - 16 decimal places. * calculates the inverse square root of the given number and returns true if calculated answer * matches with given answer else returns false */ public static boolean inverseSqrt(double number) { double x = number; double xhalf = 0.5d * x; long i = Double.doubleToLongBits(x); i = 0x5fe6ec85e7de30daL - (i >> 1); x = Double.longBitsToDouble(i); for (int it = 0; it < 4; it++) { x = x * (1.5d - xhalf * x * x); } x *= number; return x == 1 / Math.sqrt(number); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SieveOfAtkin.java
src/main/java/com/thealgorithms/maths/SieveOfAtkin.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; /** * Implementation of the Sieve of Atkin, an optimized algorithm to generate * all prime numbers up to a given limit. * * The Sieve of Atkin uses quadratic forms and modular arithmetic to identify * prime candidates, then eliminates multiples of squares. It is more efficient * than the Sieve of Eratosthenes for large limits. */ public final class SieveOfAtkin { private SieveOfAtkin() { // Utility class; prevent instantiation } /** * Generates a list of all prime numbers up to the specified limit * using the Sieve of Atkin algorithm. * * @param limit the upper bound up to which primes are generated; must be zero or positive * @return a list of prime numbers up to the limit; empty if the limit is less than 2 */ public static List<Integer> generatePrimes(int limit) { if (limit < 1) { return List.of(); } boolean[] sieve = new boolean[limit + 1]; int sqrtLimit = (int) Math.sqrt(limit); markQuadraticResidues(limit, sqrtLimit, sieve); eliminateMultiplesOfSquares(limit, sqrtLimit, sieve); List<Integer> primes = new ArrayList<>(); if (limit >= 2) { primes.add(2); } if (limit >= 3) { primes.add(3); } for (int i = 5; i <= limit; i++) { if (sieve[i]) { primes.add(i); } } return primes; } /** * Marks numbers in the sieve as prime candidates based on quadratic residues. * * This method iterates over all x and y up to sqrt(limit) and applies * the three quadratic forms used in the Sieve of Atkin. Numbers satisfying * the modulo conditions are toggled in the sieve array. * * @param limit the upper bound for primes * @param sqrtLimit square root of the limit * @param sieve boolean array representing potential primes */ private static void markQuadraticResidues(int limit, int sqrtLimit, boolean[] sieve) { for (int x = 1; x <= sqrtLimit; x++) { for (int y = 1; y <= sqrtLimit; y++) { applyQuadraticForm(4 * x * x + y * y, limit, sieve, 1, 5); applyQuadraticForm(3 * x * x + y * y, limit, sieve, 7); applyQuadraticForm(3 * x * x - y * y, limit, sieve, 11, x > y); } } } /** * Toggles the sieve entry for a number if it satisfies one modulo condition. * * @param n the number to check * @param limit upper bound of primes * @param sieve boolean array representing potential primes * @param modulo the modulo condition number to check */ private static void applyQuadraticForm(int n, int limit, boolean[] sieve, int modulo) { if (n <= limit && n % 12 == modulo) { sieve[n] ^= true; } } /** * Toggles the sieve entry for a number if it satisfies either of two modulo conditions. * * @param n the number to check * @param limit upper bound of primes * @param sieve boolean array representing potential primes * @param modulo1 first modulo condition number to check * @param modulo2 second modulo condition number to check */ private static void applyQuadraticForm(int n, int limit, boolean[] sieve, int modulo1, int modulo2) { if (n <= limit && (n % 12 == modulo1 || n % 12 == modulo2)) { sieve[n] ^= true; } } /** * Toggles the sieve entry for a number if it satisfies the modulo condition and an additional boolean condition. * * This version is used for the quadratic form 3*x*x - y*y, which requires x > y. * * @param n the number to check * @param limit upper bound of primes * @param sieve boolean array representing potential primes * @param modulo the modulo condition number to check * @param condition an additional boolean condition that must be true */ private static void applyQuadraticForm(int n, int limit, boolean[] sieve, int modulo, boolean condition) { if (condition && n <= limit && n % 12 == modulo) { sieve[n] ^= true; } } /** * Eliminates numbers that are multiples of squares from the sieve. * * All numbers that are multiples of i*i (where i is marked as prime) are * marked non-prime to finalize the sieve. This ensures only actual primes remain. * * @param limit the upper bound for primes * @param sqrtLimit square root of the limit * @param sieve boolean array representing potential primes */ private static void eliminateMultiplesOfSquares(int limit, int sqrtLimit, boolean[] sieve) { for (int i = 5; i <= sqrtLimit; i++) { if (!sieve[i]) { continue; } int square = i * i; for (int j = square; j <= limit; j += square) { sieve[j] = false; } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/KeithNumber.java
src/main/java/com/thealgorithms/maths/KeithNumber.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; /** * A Keith number is an n-digit positive integer where the sequence formed by * starting with its digits and repeatedly adding the previous n terms, * eventually reaches the number itself. * * <p> * For example: * <ul> * <li>14 is a Keith number: 1, 4, 5, 9, 14</li> * <li>19 is a Keith number: 1, 9, 10, 19</li> * <li>28 is a Keith number: 2, 8, 10, 18, 28</li> * <li>197 is a Keith number: 1, 9, 7, 17, 33, 57, 107, 197</li> * </ul> * * @see <a href="https://en.wikipedia.org/wiki/Keith_number">Keith Number - * Wikipedia</a> * @see <a href="https://mathworld.wolfram.com/KeithNumber.html">Keith Number - * MathWorld</a> */ public final class KeithNumber { private KeithNumber() { } /** * Checks if a given number is a Keith number. * * <p> * The algorithm works as follows: * <ol> * <li>Extract all digits of the number and store them in a list</li> * <li>Generate subsequent terms by summing the last n digits</li> * <li>Continue until a term equals or exceeds the original number</li> * <li>If a term equals the number, it is a Keith number</li> * </ol> * * @param number the number to check (must be positive) * @return {@code true} if the number is a Keith number, {@code false} otherwise * @throws IllegalArgumentException if the number is not positive */ public static boolean isKeith(int number) { if (number <= 0) { throw new IllegalArgumentException("Number must be positive"); } // Extract digits and store them in the list ArrayList<Integer> terms = new ArrayList<>(); int temp = number; int digitCount = 0; while (temp > 0) { terms.add(temp % 10); temp = temp / 10; digitCount++; } // Reverse the list to get digits in correct order Collections.reverse(terms); // Generate subsequent terms in the sequence int nextTerm = 0; int currentIndex = digitCount; while (nextTerm < number) { nextTerm = 0; // Sum the last 'digitCount' terms for (int j = 1; j <= digitCount; j++) { nextTerm = nextTerm + terms.get(currentIndex - j); } terms.add(nextTerm); currentIndex++; } // Check if the generated term equals the original number return (nextTerm == number); } /** * Main method for demonstrating Keith number detection. * Reads a number from standard input and checks if it is a Keith number. * * @param args command line arguments (not used) */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a positive integer: "); int number = scanner.nextInt(); if (isKeith(number)) { System.out.println("Yes, " + number + " is a Keith number."); } else { System.out.println("No, " + number + " is not a Keith number."); } scanner.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AbundantNumber.java
src/main/java/com/thealgorithms/maths/AbundantNumber.java
package com.thealgorithms.maths; /** * In number theory, an abundant number or excessive number is a positive integer for which * the sum of its proper divisors is greater than the number. * Equivalently, it is a number for which the sum of proper divisors (or aliquot sum) is greater than n. * * The integer 12 is the first abundant number. Its proper divisors are 1, 2, 3, 4 and 6 for a total of 16. * * Wiki: https://en.wikipedia.org/wiki/Abundant_number */ public final class AbundantNumber { private AbundantNumber() { } // Function to calculate sum of all divisors including n private static int sumOfDivisors(int n) { int sum = 1 + n; // 1 and n are always divisors for (int i = 2; i <= n / 2; i++) { if (n % i == 0) { sum += i; // adding divisor to sum } } return sum; } // Common validation method private static void validatePositiveNumber(int number) { if (number <= 0) { throw new IllegalArgumentException("Number must be positive."); } } /** * Check if {@code number} is an Abundant number or not by checking sum of divisors > 2n * * @param number the number * @return {@code true} if {@code number} is an Abundant number, otherwise false */ public static boolean isAbundant(int number) { validatePositiveNumber(number); return sumOfDivisors(number) > 2 * number; } /** * Check if {@code number} is an Abundant number or not by checking Aliquot Sum > n * * @param number the number * @return {@code true} if {@code number} is a Abundant number, otherwise false */ public static boolean isAbundantNumber(int number) { validatePositiveNumber(number); return AliquotSum.getAliquotSum(number) > number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java
src/main/java/com/thealgorithms/maths/LeastCommonMultiple.java
package com.thealgorithms.maths; /** * Is a common mathematics concept to find the smallest value number * that can be divide using either number without having the remainder. * https://maticschool.blogspot.com/2013/11/find-least-common-multiple-lcm.html * @author LauKinHoong */ public final class LeastCommonMultiple { private LeastCommonMultiple() { } /** * Finds the least common multiple of two numbers. * * @param num1 The first number. * @param num2 The second number. * @return The least common multiple of num1 and num2. */ public static int lcm(int num1, int num2) { int high; int num3; int cmv = 0; if (num1 > num2) { high = num1; num3 = num1; } else { high = num2; num3 = num2; } while (num1 != 0) { if (high % num1 == 0 && high % num2 == 0) { cmv = high; break; } high += num3; } return cmv; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/BinaryPow.java
src/main/java/com/thealgorithms/maths/BinaryPow.java
package com.thealgorithms.maths; public final class BinaryPow { private BinaryPow() { } /** * Calculate a^p using binary exponentiation * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) * * @param a the base for exponentiation * @param p the exponent - must be greater than 0 * @return a^p */ public static int binPow(int a, int p) { int res = 1; while (p > 0) { if ((p & 1) == 1) { res = res * a; } a = a * a; p >>>= 1; } return res; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/MagicSquare.java
src/main/java/com/thealgorithms/maths/MagicSquare.java
package com.thealgorithms.maths; import java.util.Scanner; /*A magic square of order n is an arrangement of distinct n^2 integers,in a square, such that the n numbers in all rows, all columns, and both diagonals sum to the same constant. A magic square contains the integers from 1 to n^2.*/ public final class MagicSquare { private MagicSquare() { } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input a number: "); int num = sc.nextInt(); if ((num % 2 == 0) || (num <= 0)) { System.out.print("Input number must be odd and >0"); System.exit(0); } int[][] magicSquare = new int[num][num]; int rowNum = num / 2; int colNum = num - 1; magicSquare[rowNum][colNum] = 1; for (int i = 2; i <= num * num; i++) { if (magicSquare[(rowNum - 1 + num) % num][(colNum + 1) % num] == 0) { rowNum = (rowNum - 1 + num) % num; colNum = (colNum + 1) % num; } else { colNum = (colNum - 1 + num) % num; } magicSquare[rowNum][colNum] = i; } // print the square for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { if (magicSquare[i][j] < 10) { System.out.print(" "); } if (magicSquare[i][j] < 100) { System.out.print(" "); } System.out.print(magicSquare[i][j] + " "); } System.out.println(); } sc.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PerfectSquare.java
src/main/java/com/thealgorithms/maths/PerfectSquare.java
package com.thealgorithms.maths; /** * https://en.wikipedia.org/wiki/Perfect_square */ public final class PerfectSquare { private PerfectSquare() { } /** * Check if a number is perfect square number * * @param number the number to be checked * @return <tt>true</tt> if {@code number} is perfect square, otherwise * <tt>false</tt> */ public static boolean isPerfectSquare(final int number) { final int sqrt = (int) Math.sqrt(number); return sqrt * sqrt == number; } /** * Check if a number is perfect square or not * * @param number number to be checked * @return {@code true} if {@code number} is perfect square, otherwise * {@code false} */ public static boolean isPerfectSquareUsingPow(long number) { long a = (long) Math.pow(number, 1.0 / 2); return a * a == number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java
src/main/java/com/thealgorithms/maths/StrobogrammaticNumber.java
package com.thealgorithms.maths; import java.util.HashMap; import java.util.Map; /** * A strobogrammatic number is a number that remains the same when rotated 180 degrees. * In other words, the number looks the same when rotated upside down. * Examples of strobogrammatic numbers are "69", "88", "818", and "101". * Numbers like "609" or "120" are not strobogrammatic because they do not look the same when rotated. */ public class StrobogrammaticNumber { /** * Check if a number is strobogrammatic * @param number the number to be checked * @return true if the number is strobogrammatic, false otherwise */ public boolean isStrobogrammatic(String number) { Map<Character, Character> strobogrammaticMap = new HashMap<>(); strobogrammaticMap.put('0', '0'); strobogrammaticMap.put('1', '1'); strobogrammaticMap.put('6', '9'); strobogrammaticMap.put('8', '8'); strobogrammaticMap.put('9', '6'); int left = 0; int right = number.length() - 1; while (left <= right) { char leftChar = number.charAt(left); char rightChar = number.charAt(right); if (!strobogrammaticMap.containsKey(leftChar) || strobogrammaticMap.get(leftChar) != rightChar) { return false; } left++; right--; } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Combinations.java
src/main/java/com/thealgorithms/maths/Combinations.java
package com.thealgorithms.maths; /** * @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a> */ public final class Combinations { private Combinations() { } /** * Calculate of factorial * * @param n the number * @return factorial of given number */ public static long factorial(int n) { if (n < 0) { throw new IllegalArgumentException("number is negative"); } return n == 0 || n == 1 ? 1 : n * factorial(n - 1); } /** * Calculate combinations * * @param n first number * @param k second number * @return combinations of given {@code n} and {@code k} */ public static long combinations(int n, int k) { return factorial(n) / (factorial(k) * factorial(n - k)); } /** * The above method can exceed limit of long (overflow) when factorial(n) is * larger than limits of long variable. Thus even if nCk is within range of * long variable above reason can lead to incorrect result. This is an * optimized version of computing combinations. Observations: nC(k + 1) = (n * - k) * nCk / (k + 1) We know the value of nCk when k = 1 which is nCk = n * Using this base value and above formula we can compute the next term * nC(k+1) * * @param n * @param k * @return nCk */ public static long combinationsOptimized(int n, int k) { if (n < 0 || k < 0) { throw new IllegalArgumentException("n or k can't be negative"); } if (n < k) { throw new IllegalArgumentException("n can't be smaller than k"); } // nC0 is always 1 long solution = 1; for (int i = 0; i < k; i++) { solution = (n - i) * solution / (i + 1); } return solution; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/CrossCorrelation.java
src/main/java/com/thealgorithms/maths/CrossCorrelation.java
package com.thealgorithms.maths; /** * Class for linear cross-correlation of two discrete signals * * @author Athina-Frederiki Swinkels * @version 1.0 */ public final class CrossCorrelation { private CrossCorrelation() { } /** * Discrete linear cross-correlation function. * Input and output signals have starting index 0. * * @param x The first discrete signal * @param y The second discrete signal * @return The result of the cross-correlation of signals x,y. The result is also a signal. */ public static double[] crossCorrelation(double[] x, double[] y) { // The result signal's length is the sum of the input signals' lengths minus 1 double[] result = new double[x.length + y.length - 1]; int n = result.length; /* To find the cross-correlation between 2 discrete signals x & y, we start by "placing" the second signal y under the first signal x, shifted to the left so that the last value of y meets the first value of x and for every new position (i++) of the result signal, we shift y signal one position to the right, until the first y-value meets the last x-value. The result-value for each position is the sum of all x*y meeting values. Here's an example: x=[1,2,1,1] y=[1,1,2,1] i=0: [1,2,1,1] [1,1,2,1] result[0]=1*1=1 i=1: [1,2,1,1] [1,1,2,1] result[1]=1*2+2*1=4 i=2: [1,2,1,1] [1,1,2,1] result[2]=1*1+2*2+1*1=6 i=3: [1,2,1,1] [1,1,2,1] result[3]=1*1+2*1+1*2+1*1=6 i=4: [1,2,1,1] [1,1,2,1] result[4]=2*1+1*1+1*2=5 i=5: [1,2,1,1] [1,1,2,1] result[5]=1*1+1*1=2 i=1: [1,2,1,1] [1,1,2,1] result[6]=1*1=1 result=[1,4,6,6,5,2,1] To find the result[i] value for each i:0->n-1, the positions of x-signal in which the 2 signals meet are calculated: kMin<=k<=kMax. The variable 'yStart' indicates the starting index of y in each sum calculation. The variable 'count' increases the index of y-signal by 1, to move to the next value. */ int yStart = y.length; for (int i = 0; i < n; i++) { result[i] = 0; int kMin = Math.max(i - (y.length - 1), 0); int kMax = Math.min(i, x.length - 1); if (i < y.length) { yStart--; } int count = 0; for (int k = kMin; k <= kMax; k++) { result[i] += x[k] * y[yStart + count]; count++; } } // The calculated cross-correlation of x & y signals is returned here. return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/NumberOfDigits.java
src/main/java/com/thealgorithms/maths/NumberOfDigits.java
package com.thealgorithms.maths; /** * Find the number of digits in a number. */ public final class NumberOfDigits { private NumberOfDigits() { } /** * Find the number of digits in a number. * * @param number number to find * @return number of digits of given number */ public static int numberOfDigits(int number) { int digits = 0; do { digits++; number /= 10; } while (number != 0); return digits; } /** * Find the number of digits in a number fast version. * * @param number number to find * @return number of digits of given number */ public static int numberOfDigitsFast(int number) { return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1); } /** * Find the number of digits in a number faster version. * * @param number number to find * @return number of digits of given number */ public static int numberOfDigitsFaster(int number) { return number < 0 ? (-number + "").length() : (number + "").length(); } /** * Find the number of digits in a number using recursion. * * @param number number to find * @return number of digits of given number */ public static int numberOfDigitsRecursion(int number) { return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Ceil.java
src/main/java/com/thealgorithms/maths/Ceil.java
package com.thealgorithms.maths; /** * Utility class to compute the ceiling of a given number. */ public final class Ceil { private Ceil() { } /** * Returns the smallest double value that is greater than or equal to the input. * Equivalent to mathematical ⌈x⌉ (ceiling function). * * @param number the number to ceil * @return the smallest double greater than or equal to {@code number} */ public static double ceil(double number) { if (Double.isNaN(number) || Double.isInfinite(number) || number == 0.0 || number < Integer.MIN_VALUE || number > Integer.MAX_VALUE) { return number; } if (number < 0.0 && number > -1.0) { return -0.0; } long intPart = (long) number; if (number > 0 && number != intPart) { return intPart + 1.0; } else { return intPart; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PalindromeNumber.java
src/main/java/com/thealgorithms/maths/PalindromeNumber.java
package com.thealgorithms.maths; public final class PalindromeNumber { private PalindromeNumber() { } /** * Check if {@code n} is palindrome number or not * * @param number the number * @return {@code true} if {@code n} is palindrome number, otherwise * {@code false} */ public static boolean isPalindrome(int number) { if (number < 0) { throw new IllegalArgumentException("Input parameter must not be negative!"); } int numberCopy = number; int reverseNumber = 0; while (numberCopy != 0) { int remainder = numberCopy % 10; reverseNumber = reverseNumber * 10 + remainder; numberCopy /= 10; } return number == reverseNumber; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java
src/main/java/com/thealgorithms/maths/SumOfOddNumbers.java
package com.thealgorithms.maths; /** * This program calculates the sum of the first n odd numbers. * * https://www.cuemath.com/algebra/sum-of-odd-numbers/ */ public final class SumOfOddNumbers { private SumOfOddNumbers() { } /** * Calculate sum of the first n odd numbers * * @param n the number of odd numbers to sum * @return sum of the first n odd numbers */ public static int sumOfFirstNOddNumbers(final int n) { if (n < 0) { throw new IllegalArgumentException("n must be non-negative."); } return n * n; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FindMin.java
src/main/java/com/thealgorithms/maths/FindMin.java
package com.thealgorithms.maths; public final class FindMin { private FindMin() { } /** * @brief finds the minimum value stored in the input array * * @param array the input array * @exception IllegalArgumentException input array is empty * @return the mimum value stored in the input array */ public static int findMin(final int[] array) { if (array.length == 0) { throw new IllegalArgumentException("Array must be non-empty."); } int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Perimeter.java
src/main/java/com/thealgorithms/maths/Perimeter.java
package com.thealgorithms.maths; // Perimeter of different 2D geometrical shapes public final class Perimeter { private Perimeter() { } /** * Calculate the Perimeter of regular polygon (equals sides) * Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular * Hexagon. * * @param n for number of sides. * @param side for length of each side. * @return Perimeter of given polygon */ public static float perimeterRegularPolygon(int n, float side) { return n * side; } /** * Calculate the Perimeter of irregular polygon (unequals sides) * Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular * Pentagon, irregular Hexagon. * * @param side1 for length of side 1 * @param side2 for length of side 2 * @param side3 for length of side 3 * @param sides for length of remaining sides * @return Perimeter of given irregular polygon. */ public static float perimeterIrregularPolygon(float side1, float side2, float side3, float... sides) { float perimeter = side1 + side2 + side3; for (float side : sides) { perimeter += side; } return perimeter; } /** * Calculate the Perimeter of rectangle * * @param length for length of rectangle * @param breadth for breadth of rectangle * @return Perimeter of given rectangle */ public static float perimeterRectangle(float length, float breadth) { return 2 * (length + breadth); } /** * Calculate the Perimeter or Circumference of circle. * * @param r for radius of circle. * @return circumference of given circle. */ public static double perimeterCircle(float r) { return 2 * Math.PI * r; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ParseInteger.java
src/main/java/com/thealgorithms/maths/ParseInteger.java
package com.thealgorithms.maths; public final class ParseInteger { private ParseInteger() { } private static void checkInput(final String s) { if (s == null) { throw new NumberFormatException("Input parameter must not be null!"); } if (s.isEmpty()) { throw new NumberFormatException("Input parameter must not be empty!"); } } private static void checkDigitAt(final String s, final int pos) { if (!Character.isDigit(s.charAt(pos))) { throw new NumberFormatException("Input parameter of incorrect format: " + s); } } private static int digitToInt(final char digit) { return digit - '0'; } /** * Parse a string to integer * * @param s the string * @return the integer value represented by the argument in decimal. * @throws NumberFormatException if the {@code string} does not contain a * parsable integer. */ public static int parseInt(final String s) { checkInput(s); final boolean isNegative = s.charAt(0) == '-'; final boolean isPositive = s.charAt(0) == '+'; int number = 0; for (int i = isNegative || isPositive ? 1 : 0, length = s.length(); i < length; ++i) { checkDigitAt(s, i); number = number * 10 + digitToInt(s.charAt(i)); } return isNegative ? -number : number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/EulerMethod.java
src/main/java/com/thealgorithms/maths/EulerMethod.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.function.BiFunction; /** * In mathematics and computational science, the Euler method (also called * forward Euler method) is a first-order numerical procedure for solving * ordinary differential equations (ODEs) with a given initial value. It is the * most basic explicit method for numerical integration of ordinary differential * equations. The method proceeds in a series of steps. At each step the y-value * is calculated by evaluating the differential equation at the previous step, * multiplying the result with the step-size and adding it to the last y-value: * y_n+1 = y_n + stepSize * f(x_n, y_n). (description adapted from * https://en.wikipedia.org/wiki/Euler_method ) (see also: * https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ ) */ public final class EulerMethod { private EulerMethod() { } /** * Illustrates how the algorithm is used in 3 examples and prints the * results to the console. */ public static void main(String[] args) { System.out.println("example 1:"); BiFunction<Double, Double, Double> exampleEquation1 = (x, y) -> x; ArrayList<double[]> points1 = eulerFull(0, 4, 0.1, 0, exampleEquation1); assert points1.get(points1.size() - 1)[1] == 7.800000000000003; points1.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1])); // example from https://en.wikipedia.org/wiki/Euler_method System.out.println("\n\nexample 2:"); BiFunction<Double, Double, Double> exampleEquation2 = (x, y) -> y; ArrayList<double[]> points2 = eulerFull(0, 4, 0.1, 1, exampleEquation2); assert points2.get(points2.size() - 1)[1] == 45.25925556817596; points2.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1])); // example from https://www.geeksforgeeks.org/euler-method-solving-differential-equation/ System.out.println("\n\nexample 3:"); BiFunction<Double, Double, Double> exampleEquation3 = (x, y) -> x + y + x * y; ArrayList<double[]> points3 = eulerFull(0, 0.1, 0.025, 1, exampleEquation3); assert points3.get(points3.size() - 1)[1] == 1.1116729841674804; points3.forEach(point -> System.out.printf("x: %1$f; y: %2$f%n", point[0], point[1])); } /** * calculates the next y-value based on the current value of x, y and the * stepSize the console. * * @param xCurrent Current x-value. * @param stepSize Step-size on the x-axis. * @param yCurrent Current y-value. * @param differentialEquation The differential equation to be solved. * @return The next y-value. */ public static double eulerStep(double xCurrent, double stepSize, double yCurrent, BiFunction<Double, Double, Double> differentialEquation) { if (stepSize <= 0) { throw new IllegalArgumentException("stepSize should be greater than zero"); } return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent); } /** * Loops through all the steps until xEnd is reached, adds a point for each * step and then returns all the points * * @param xStart First x-value. * @param xEnd Last x-value. * @param stepSize Step-size on the x-axis. * @param yStart First y-value. * @param differentialEquation The differential equation to be solved. * @return The points constituting the solution of the differential * equation. */ public static ArrayList<double[]> eulerFull(double xStart, double xEnd, double stepSize, double yStart, BiFunction<Double, Double, Double> differentialEquation) { if (xStart >= xEnd) { throw new IllegalArgumentException("xEnd should be greater than xStart"); } if (stepSize <= 0) { throw new IllegalArgumentException("stepSize should be greater than zero"); } ArrayList<double[]> points = new ArrayList<double[]>(); double[] firstPoint = {xStart, yStart}; points.add(firstPoint); double yCurrent = yStart; double xCurrent = xStart; while (xCurrent < xEnd) { // Euler's method for next step yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation); xCurrent += stepSize; double[] point = {xCurrent, yCurrent}; points.add(point); } return points; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ConvolutionFFT.java
src/main/java/com/thealgorithms/maths/ConvolutionFFT.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collection; /** * Class for linear convolution of two discrete signals using the convolution * theorem. * * @author Ioannis Karavitsis * @version 1.0 */ public final class ConvolutionFFT { private ConvolutionFFT() { } /** * This method pads the signal with zeros until it reaches the new size. * * @param x The signal to be padded. * @param newSize The new size of the signal. */ private static void padding(Collection<FFT.Complex> x, int newSize) { if (x.size() < newSize) { int diff = newSize - x.size(); for (int i = 0; i < diff; i++) { x.add(new FFT.Complex()); } } } /** * Discrete linear convolution function. It uses the convolution theorem for * discrete signals convolved: = IDFT(DFT(a)*DFT(b)). This is true for * circular convolution. In order to get the linear convolution of the two * signals we first pad the two signals to have the same size equal to the * convolved signal (a.size() + b.size() - 1). Then we use the FFT algorithm * for faster calculations of the two DFTs and the final IDFT. * * <p> * More info: https://en.wikipedia.org/wiki/Convolution_theorem * https://ccrma.stanford.edu/~jos/ReviewFourier/FFT_Convolution.html * * @param a The first signal. * @param b The other signal. * @return The convolved signal. */ public static ArrayList<FFT.Complex> convolutionFFT(ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) { int convolvedSize = a.size() + b.size() - 1; // The size of the convolved signal padding(a, convolvedSize); // Zero padding both signals padding(b, convolvedSize); /* Find the FFTs of both signals (Note that the size of the FFTs will be bigger than the * convolvedSize because of the extra zero padding in FFT algorithm) */ FFT.fft(a, false); FFT.fft(b, false); ArrayList<FFT.Complex> convolved = new ArrayList<>(); for (int i = 0; i < a.size(); i++) { convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b) } FFT.fft(convolved, true); // IFFT convolved.subList(convolvedSize, convolved.size()).clear(); // Remove the remaining zeros after the convolvedSize. These extra zeros came // from // paddingPowerOfTwo() method inside the fft() method. return convolved; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Average.java
src/main/java/com/thealgorithms/maths/Average.java
package com.thealgorithms.maths; /** * A utility class for computing the average of numeric arrays. * This class provides static methods to calculate the average of arrays * of both {@code double} and {@code int} values. */ public final class Average { // Prevent instantiation of this utility class private Average() { throw new UnsupportedOperationException("This is a utility class and cannot be instantiated."); } /** * Computes the average of a {@code double} array. * * @param numbers an array of {@code double} values * @return the average of the given numbers * @throws IllegalArgumentException if the input array is {@code null} or empty */ public static double average(double[] numbers) { if (numbers == null || numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty or null"); } double sum = 0; for (double number : numbers) { sum += number; } return sum / numbers.length; } /** * Computes the average of an {@code int} array. * * @param numbers an array of {@code int} values * @return the average of the given numbers * @throws IllegalArgumentException if the input array is {@code null} or empty */ public static long average(int[] numbers) { if (numbers == null || numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty or null"); } long sum = 0; for (int number : numbers) { sum += number; } return sum / numbers.length; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/TwinPrime.java
src/main/java/com/thealgorithms/maths/TwinPrime.java
package com.thealgorithms.maths; /* * Java program to find 'twin prime' of a prime number * Twin Prime: Twin prime of a number n is (n+2) * if and only if n & (n+2) are prime. * Wikipedia: https://en.wikipedia.org/wiki/Twin_prime * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ import com.thealgorithms.maths.Prime.PrimeCheck; public final class TwinPrime { private TwinPrime() { } /** * This method returns twin prime of the integer value passed as argument * * @param inputNumber Integer value of which twin prime is to be found * @return (number + 2) if number and (number + 2) are prime, -1 otherwise */ static int getTwinPrime(int inputNumber) { // if inputNumber and (inputNumber + 2) are both prime // then return (inputNumber + 2) as a result if (PrimeCheck.isPrime(inputNumber) && PrimeCheck.isPrime(inputNumber + 2)) { return inputNumber + 2; } // if any one from inputNumber and (inputNumber + 2) or if both of them are not prime // then return -1 as a result return -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Neville.java
src/main/java/com/thealgorithms/maths/Neville.java
package com.thealgorithms.maths; import java.util.HashSet; import java.util.Set; /** * In numerical analysis, Neville's algorithm is an algorithm used for * polynomial interpolation. Given n+1 points, there is a unique polynomial of * degree at most n that passes through all the points. Neville's algorithm * computes the value of this polynomial at a given point. * * <p> * Wikipedia: https://en.wikipedia.org/wiki/Neville%27s_algorithm * * @author Mitrajit Ghorui(KeyKyrios) */ public final class Neville { private Neville() { } /** * Evaluates the polynomial that passes through the given points at a * specific x-coordinate. * * @param x The x-coordinates of the points. Must be the same length as y. * @param y The y-coordinates of the points. Must be the same length as x. * @param target The x-coordinate at which to evaluate the polynomial. * @return The interpolated y-value at the target x-coordinate. * @throws IllegalArgumentException if the lengths of x and y arrays are * different, if the arrays are empty, or if x-coordinates are not unique. */ public static double interpolate(double[] x, double[] y, double target) { if (x.length != y.length) { throw new IllegalArgumentException("x and y arrays must have the same length."); } if (x.length == 0) { throw new IllegalArgumentException("Input arrays cannot be empty."); } // Check for duplicate x-coordinates to prevent division by zero Set<Double> seenX = new HashSet<>(); for (double val : x) { if (!seenX.add(val)) { throw new IllegalArgumentException("Input x-coordinates must be unique."); } } int n = x.length; double[] p = new double[n]; System.arraycopy(y, 0, p, 0, n); // Initialize p with y values for (int k = 1; k < n; k++) { for (int i = 0; i < n - k; i++) { p[i] = ((target - x[i + k]) * p[i] + (x[i] - target) * p[i + 1]) / (x[i] - x[i + k]); } } return p[0]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/HarshadNumber.java
src/main/java/com/thealgorithms/maths/HarshadNumber.java
package com.thealgorithms.maths; /** * A Harshad number (or Niven number) in a given number base is an integer that * is divisible by the sum of its digits. * For example, 18 is a Harshad number because 18 is divisible by (1 + 8) = 9. * The name "Harshad" comes from the Sanskrit words "harṣa" (joy) and "da" * (give), meaning "joy-giver". * * @author <a href="https://github.com/Hardvan">Hardvan</a> * @see <a href="https://en.wikipedia.org/wiki/Harshad_number">Harshad Number - * Wikipedia</a> */ public final class HarshadNumber { private HarshadNumber() { } /** * Checks if a number is a Harshad number. * A Harshad number is a positive integer that is divisible by the sum of its * digits. * * @param n the number to be checked (must be positive) * @return {@code true} if {@code n} is a Harshad number, otherwise * {@code false} * @throws IllegalArgumentException if {@code n} is less than or equal to 0 */ public static boolean isHarshad(long n) { if (n <= 0) { throw new IllegalArgumentException("Input must be a positive integer. Received: " + n); } long temp = n; long sumOfDigits = 0; while (temp > 0) { sumOfDigits += temp % 10; temp /= 10; } return n % sumOfDigits == 0; } /** * Checks if a number represented as a string is a Harshad number. * A Harshad number is a positive integer that is divisible by the sum of its * digits. * * @param s the string representation of the number to be checked * @return {@code true} if the number is a Harshad number, otherwise * {@code false} * @throws IllegalArgumentException if {@code s} is null, empty, or represents a * non-positive integer * @throws NumberFormatException if {@code s} cannot be parsed as a long */ public static boolean isHarshad(String s) { if (s == null || s.isEmpty()) { throw new IllegalArgumentException("Input string cannot be null or empty"); } final long n; try { n = Long.parseLong(s); } catch (NumberFormatException e) { throw new IllegalArgumentException("Input string must be a valid integer: " + s, e); } if (n <= 0) { throw new IllegalArgumentException("Input must be a positive integer. Received: " + n); } int sumOfDigits = 0; for (char ch : s.toCharArray()) { if (Character.isDigit(ch)) { sumOfDigits += ch - '0'; } } return n % sumOfDigits == 0; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/MinValue.java
src/main/java/com/thealgorithms/maths/MinValue.java
package com.thealgorithms.maths; public final class MinValue { private MinValue() { } /** * Returns the smaller of two {@code int} values. That is, the result the * argument closer to the value of {@link Integer#MIN_VALUE}. If the * arguments have the same value, the result is that same value. * * @param a an argument. * @param b another argument. * @return the smaller of {@code a} and {@code b}. */ public static int min(int a, int b) { return a <= b ? a : b; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LucasSeries.java
src/main/java/com/thealgorithms/maths/LucasSeries.java
package com.thealgorithms.maths; /** * Utility class for calculating Lucas numbers. * The Lucas sequence is similar to the Fibonacci sequence but starts with 2 and * 1. * The sequence follows: L(n) = L(n-1) + L(n-2) * Starting values: L(1) = 2, L(2) = 1 * Sequence: 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ... * * @see <a href="https://en.wikipedia.org/wiki/Lucas_number">Lucas Number</a> * @author TheAlgorithms Contributors */ public final class LucasSeries { private LucasSeries() { } /** * Calculate the nth Lucas number using recursion. * Time Complexity: O(2^n) - exponential due to recursive calls * Space Complexity: O(n) - recursion depth * * @param n the position in the Lucas sequence (1-indexed, must be positive) * @return the nth Lucas number * @throws IllegalArgumentException if n is less than 1 */ public static int lucasSeries(int n) { if (n < 1) { throw new IllegalArgumentException("Input must be a positive integer. Provided: " + n); } if (n == 1) { return 2; } if (n == 2) { return 1; } return lucasSeries(n - 1) + lucasSeries(n - 2); } /** * Calculate the nth Lucas number using iteration. * Time Complexity: O(n) - single loop through n iterations * Space Complexity: O(1) - constant space usage * * @param n the position in the Lucas sequence (1-indexed, must be positive) * @return the nth Lucas number * @throws IllegalArgumentException if n is less than 1 */ public static int lucasSeriesIteration(int n) { if (n < 1) { throw new IllegalArgumentException("Input must be a positive integer. Provided: " + n); } if (n == 1) { return 2; } if (n == 2) { return 1; } int previous = 2; int current = 1; for (int i = 2; i < n; i++) { int next = previous + current; previous = current; current = next; } return current; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/EulerPseudoprime.java
src/main/java/com/thealgorithms/maths/EulerPseudoprime.java
package com.thealgorithms.maths; import java.math.BigInteger; import java.util.Random; /** * The {@code EulerPseudoprime} class implements the Euler primality test. * * It is based on Euler’s criterion: * For an odd prime number {@code n} and any integer {@code a} coprime to {@code n}: * a^((n-1)/2) ≡ (a/n) (mod n) * where (a/n) is the Jacobi symbol. * * This algorithm is a stronger probabilistic test than Fermat’s test. * It may still incorrectly identify a composite as “probably prime” (Euler pseudoprime), * but such cases are rare. */ public final class EulerPseudoprime { private EulerPseudoprime() { // Private constructor to prevent instantiation. } private static final Random RANDOM = new Random(1); /** * Performs the Euler primality test for a given number. * * @param n number to test (must be > 2 and odd) * @param trials number of random bases to test * @return {@code true} if {@code n} passes all Euler tests (probably prime), * {@code false} if composite. */ public static boolean isProbablePrime(BigInteger n, int trials) { if (n.compareTo(BigInteger.TWO) < 0) { return false; } if (n.equals(BigInteger.TWO) || n.equals(BigInteger.valueOf(3))) { return true; } if (n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) { return false; } for (int i = 0; i < trials; i++) { BigInteger a = uniformRandom(BigInteger.TWO, n.subtract(BigInteger.TWO)); BigInteger jacobi = BigInteger.valueOf(jacobiSymbol(a, n)); if (jacobi.equals(BigInteger.ZERO)) { return false; } BigInteger exp = n.subtract(BigInteger.ONE).divide(BigInteger.TWO); BigInteger modExp = a.modPow(exp, n); // Euler's criterion: a^((n-1)/2) ≡ (a/n) (mod n) if (!modExp.equals(jacobi.mod(n))) { return false; // definitely composite } } return true; // probably prime } /** * Computes the Jacobi symbol (a/n). * Assumes n is positive and odd. */ public static int jacobiSymbol(BigInteger a, BigInteger n) { if (n.signum() <= 0 || n.mod(BigInteger.TWO).equals(BigInteger.ZERO)) { throw new IllegalArgumentException("n must be positive and odd."); } int result = 1; a = a.mod(n); while (a.compareTo(BigInteger.ZERO) != 0) { while (a.mod(BigInteger.TWO).equals(BigInteger.ZERO)) { a = a.divide(BigInteger.TWO); BigInteger nMod8 = n.mod(BigInteger.valueOf(8)); if (nMod8.equals(BigInteger.valueOf(3)) || nMod8.equals(BigInteger.valueOf(5))) { result = -result; } } BigInteger temp = a; a = n; n = temp; if (a.mod(BigInteger.valueOf(4)).equals(BigInteger.valueOf(3)) && n.mod(BigInteger.valueOf(4)).equals(BigInteger.valueOf(3))) { result = -result; } a = a.mod(n); } return n.equals(BigInteger.ONE) ? result : 0; } /** * Generates a random BigInteger between {@code min} and {@code max}, inclusive. */ private static BigInteger uniformRandom(BigInteger min, BigInteger max) { BigInteger result; do { result = new BigInteger(max.bitLength(), RANDOM); } while (result.compareTo(min) < 0 || result.compareTo(max) > 0); return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/GCDRecursion.java
src/main/java/com/thealgorithms/maths/GCDRecursion.java
package com.thealgorithms.maths; /** * @author https://github.com/shellhub/ */ public final class GCDRecursion { private GCDRecursion() { } public static void main(String[] args) { System.out.println(gcd(20, 15)); /* output: 5 */ System.out.println(gcd(10, 8)); /* output: 2 */ System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */ } /** * get greatest common divisor * * @param a the first number * @param b the second number * @return gcd */ public static int gcd(int a, int b) { if (a < 0 || b < 0) { throw new ArithmeticException(); } if (a == 0 || b == 0) { return Math.abs(a - b); } if (a % b == 0) { return b; } else { return gcd(b, a % b); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PowerOfTwoOrNot.java
src/main/java/com/thealgorithms/maths/PowerOfTwoOrNot.java
package com.thealgorithms.maths; /** * A utility to check if a given number is power of two or not. For example 8,16 * etc. */ public final class PowerOfTwoOrNot { private PowerOfTwoOrNot() { } /** * Checks whether given number is power of two or not. * * @param number the number to check * @return {@code true} if given number is power of two, otherwise * {@code false} */ public static boolean checkIfPowerOfTwoOrNot(final int number) { return number != 0 && ((number & (number - 1)) == 0); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java
src/main/java/com/thealgorithms/maths/KrishnamurthyNumber.java
package com.thealgorithms.maths; /** * Utility class for checking if a number is a Krishnamurthy number. * * <p> * A Krishnamurthy number (also known as a Strong number or Factorion) is a * number * whose sum of the factorials of its digits is equal to the number itself. * </p> * * <p> * For example, 145 is a Krishnamurthy number because 1! + 4! + 5! = 1 + 24 + * 120 = 145. * </p> * * <p> * The only Krishnamurthy numbers in base 10 are: 1, 2, 145, and 40585. * </p> * * <p> * <b>Example usage:</b> * </p> * * <pre> * boolean isKrishnamurthy = KrishnamurthyNumber.isKrishnamurthy(145); * System.out.println(isKrishnamurthy); // Output: true * * isKrishnamurthy = KrishnamurthyNumber.isKrishnamurthy(123); * System.out.println(isKrishnamurthy); // Output: false * </pre> * * @see <a href="https://en.wikipedia.org/wiki/Factorion">Factorion * (Wikipedia)</a> */ public final class KrishnamurthyNumber { // Pre-computed factorials for digits 0-9 to improve performance private static final int[] FACTORIALS = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880}; private KrishnamurthyNumber() { } /** * Checks if a number is a Krishnamurthy number. * * <p> * A number is a Krishnamurthy number if the sum of the factorials of its digits * equals the number itself. * </p> * * @param n the number to check * @return true if the number is a Krishnamurthy number, false otherwise */ public static boolean isKrishnamurthy(int n) { if (n <= 0) { return false; } int original = n; int sum = 0; while (n != 0) { int digit = n % 10; sum = sum + FACTORIALS[digit]; n = n / 10; } return sum == original; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SecondMinMax.java
src/main/java/com/thealgorithms/maths/SecondMinMax.java
package com.thealgorithms.maths; import java.util.function.BiPredicate; public final class SecondMinMax { /** * Utility class for finding second maximum or minimum based on BiPredicate * @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same * @return the second minimum / maximum value from the input array * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) */ private SecondMinMax() { } private static int secondBest(final int[] arr, final int initialVal, final BiPredicate<Integer, Integer> isBetter) { checkInput(arr); int best = initialVal; int secBest = initialVal; for (final int num : arr) { if (isBetter.test(num, best)) { secBest = best; best = num; } else if ((isBetter.test(num, secBest)) && (num != best)) { secBest = num; } } checkOutput(secBest, initialVal); return secBest; } /** * @brief Finds the Second minimum / maximum value from the array * @param arr the input array * @exception IllegalArgumentException => if input array is of length less than 2 also if all elements are same * @return the second minimum / maximum value from the input array * @author Bharath Sanjeevi ( https://github.com/BharathSanjeeviT ) */ public static int findSecondMin(final int[] arr) { return secondBest(arr, Integer.MAX_VALUE, (a, b) -> a < b); } public static int findSecondMax(final int[] arr) { return secondBest(arr, Integer.MIN_VALUE, (a, b) -> a > b); } private static void checkInput(final int[] arr) { if (arr.length < 2) { throw new IllegalArgumentException("Input array must have length of at least two"); } } private static void checkOutput(final int secNum, final int initialVal) { if (secNum == initialVal) { throw new IllegalArgumentException("Input array should have at least 2 distinct elements"); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/TrinomialTriangle.java
src/main/java/com/thealgorithms/maths/TrinomialTriangle.java
package com.thealgorithms.maths; /** * The trinomial triangle is a variation of Pascal’s triangle. The difference * between the two is that an entry in the trinomial triangle is the sum of the * three (rather than the two in Pasacal’s triangle) entries above it * * Example Input: n = 4 Output 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 */ public final class TrinomialTriangle { private TrinomialTriangle() { } public static int trinomialValue(int n, int k) { if (n == 0 && k == 0) { return 1; } if (k < -n || k > n) { return 0; } return (trinomialValue(n - 1, k - 1) + trinomialValue(n - 1, k) + trinomialValue(n - 1, k + 1)); } public static void printTrinomial(int n) { for (int i = 0; i < n; i++) { for (int j = -i; j <= 0; j++) { System.out.print(trinomialValue(i, j) + " "); } for (int j = 1; j <= i; j++) { System.out.print(trinomialValue(i, j) + " "); } System.out.println(); } } public static void main(String[] argc) { int n = 6; printTrinomial(n); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java
src/main/java/com/thealgorithms/maths/RomanNumeralUtil.java
package com.thealgorithms.maths; /** * Translates numbers into the Roman Numeral System. * * @see <a href="https://en.wikipedia.org/wiki/Roman_numerals">Roman * numerals</a> * @author Sokratis Fotkatzikis * @version 1.0 */ public final class RomanNumeralUtil { private RomanNumeralUtil() { } private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 5999; // 1000-5999 private static final String[] RN_M = { "", "M", "MM", "MMM", "MMMM", "MMMMM", }; // 100-900 private static final String[] RN_C = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", }; // 10-90 private static final String[] RN_X = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", }; // 1-9 private static final String[] RN_I = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", }; public static String generate(int number) { if (number < MIN_VALUE || number > MAX_VALUE) { throw new IllegalArgumentException(String.format("The number must be in the range [%d, %d]", MIN_VALUE, MAX_VALUE)); } return (RN_M[number / 1000] + RN_C[number % 1000 / 100] + RN_X[number % 100 / 10] + RN_I[number % 10]); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/NonRepeatingElement.java
src/main/java/com/thealgorithms/maths/NonRepeatingElement.java
package com.thealgorithms.maths; /** * Find the 2 elements which are non-repeating in an array * Reason to use bitwise operator: It makes our program faster as we are operating on bits and not * on actual numbers. * * Explanation of the code: * Let us assume we have an array [1, 2, 1, 2, 3, 4] * Property of XOR: num ^ num = 0. * If we XOR all the elements of the array, we will be left with 3 ^ 4 as 1 ^ 1 * and 2 ^ 2 would give 0. Our task is to find num1 and num2 from the result of 3 ^ 4 = 7. * We need to find the two's complement of 7 and find the rightmost set bit, i.e., (num & (-num)). * Two's complement of 7 is 001, and hence res = 1. There can be 2 options when we Bitwise AND this res * with all the elements in our array: * 1. The result will be a non-zero number. * 2. The result will be 0. * In the first case, we will XOR our element with the first number (which is initially 0). * In the second case, we will XOR our element with the second number (which is initially 0). * This is how we will get non-repeating elements with the help of bitwise operators. */ public final class NonRepeatingElement { private NonRepeatingElement() { } /** * Finds the two non-repeating elements in the array. * * @param arr The input array containing exactly two non-repeating elements and all other elements repeating. * @return An array containing the two non-repeating elements. * @throws IllegalArgumentException if the input array length is odd. */ public static int[] findNonRepeatingElements(int[] arr) { if (arr.length % 2 != 0) { throw new IllegalArgumentException("Array should contain an even number of elements"); } int xorResult = 0; // Find XOR of all elements for (int num : arr) { xorResult ^= num; } // Find the rightmost set bit int rightmostSetBit = xorResult & (-xorResult); int num1 = 0; int num2 = 0; // Divide the elements into two groups and XOR them for (int num : arr) { if ((num & rightmostSetBit) != 0) { num1 ^= num; } else { num2 ^= num; } } return new int[] {num1, num2}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java
src/main/java/com/thealgorithms/maths/DeterminantOfMatrix.java
package com.thealgorithms.maths; /* * @author Ojasva Jain * Determinant of a Matrix Wikipedia link: https://en.wikipedia.org/wiki/Determinant */ public final class DeterminantOfMatrix { private DeterminantOfMatrix() { } /** * Calculates the determinant of a given matrix. * * @param a the input matrix * @param n the size of the matrix * @return the determinant of the matrix */ static int determinant(int[][] a, int n) { int det = 0; int sign = 1; int p = 0; int q = 0; if (n == 1) { det = a[0][0]; } else { int[][] b = new int[n - 1][n - 1]; for (int x = 0; x < n; x++) { p = 0; q = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { if (j != x) { b[p][q++] = a[i][j]; if (q % (n - 1) == 0) { p++; q = 0; } } } } det = det + a[0][x] * determinant(b, n - 1) * sign; sign = -sign; } } return det; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Floor.java
src/main/java/com/thealgorithms/maths/Floor.java
package com.thealgorithms.maths; public final class Floor { private Floor() { } /** * Returns the largest (closest to positive infinity) * * @param number the number * @return the largest (closest to positive infinity) of given * {@code number} */ public static double floor(double number) { if (number - (int) number == 0) { return number; } else if (number - (int) number > 0) { return (int) number; } else { return (int) number - 1; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java
src/main/java/com/thealgorithms/maths/LinearDiophantineEquationsSolver.java
package com.thealgorithms.maths; import java.util.Objects; /** * A solver for linear Diophantine equations of the form ax + by = c. * <p> * A linear Diophantine equation is an equation in which only integer solutions * are allowed. * This solver uses the Extended Euclidean Algorithm to find integer solutions * (x, y) * for equations of the form ax + by = c, where a, b, and c are integers. * </p> * <p> * The equation has solutions if and only if gcd(a, b) divides c. * If solutions exist, this solver finds one particular solution. * </p> * * @see <a href="https://en.wikipedia.org/wiki/Diophantine_equation">Diophantine * Equation</a> * @see <a href= * "https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm">Extended * Euclidean Algorithm</a> */ public final class LinearDiophantineEquationsSolver { private LinearDiophantineEquationsSolver() { } /** * Demonstrates the solver with a sample equation: 3x + 4y = 7. * * @param args command line arguments (not used) */ public static void main(String[] args) { // 3x + 4y = 7 final var toSolve = new Equation(3, 4, 7); System.out.println(findAnySolution(toSolve)); } /** * Finds any integer solution to the linear Diophantine equation ax + by = c. * <p> * The method returns one of three types of solutions: * <ul> * <li>A specific solution (x, y) if solutions exist</li> * <li>{@link Solution#NO_SOLUTION} if no integer solutions exist</li> * <li>{@link Solution#INFINITE_SOLUTIONS} if the equation is 0x + 0y = 0</li> * </ul> * </p> * * @param equation the linear Diophantine equation to solve * @return a Solution object containing the result * @throws NullPointerException if equation is null */ public static Solution findAnySolution(final Equation equation) { if (equation.a() == 0 && equation.b() == 0 && equation.c() == 0) { return Solution.INFINITE_SOLUTIONS; } if (equation.a() == 0 && equation.b() == 0) { return Solution.NO_SOLUTION; } if (equation.a() == 0) { if (equation.c() % equation.b() == 0) { return new Solution(0, equation.c() / equation.b()); } else { return Solution.NO_SOLUTION; } } if (equation.b() == 0) { if (equation.c() % equation.a() == 0) { return new Solution(equation.c() / equation.a(), 0); } else { return Solution.NO_SOLUTION; } } final var stub = new GcdSolutionWrapper(0, new Solution(0, 0)); final var gcdSolution = gcd(equation.a(), equation.b(), stub); if (equation.c() % gcdSolution.getGcd() != 0) { return Solution.NO_SOLUTION; } final var toReturn = new Solution(0, 0); var xToSet = stub.getSolution().getX() * (equation.c() / stub.getGcd()); var yToSet = stub.getSolution().getY() * (equation.c() / stub.getGcd()); toReturn.setX(xToSet); toReturn.setY(yToSet); return toReturn; } /** * Computes the GCD of two integers using the Extended Euclidean Algorithm. * <p> * This method also finds coefficients x and y such that ax + by = gcd(a, b). * The coefficients are stored in the 'previous' wrapper object. * </p> * * @param a the first integer * @param b the second integer * @param previous a wrapper to store the solution coefficients * @return a GcdSolutionWrapper containing the GCD and coefficients */ private static GcdSolutionWrapper gcd(final int a, final int b, final GcdSolutionWrapper previous) { if (b == 0) { return new GcdSolutionWrapper(a, new Solution(1, 0)); } // stub wrapper becomes the `previous` of the next recursive call final var stubWrapper = new GcdSolutionWrapper(0, new Solution(0, 0)); final var next = gcd(b, a % b, stubWrapper); previous.getSolution().setX(next.getSolution().getY()); previous.getSolution().setY(next.getSolution().getX() - (a / b) * (next.getSolution().getY())); previous.setGcd(next.getGcd()); return new GcdSolutionWrapper(next.getGcd(), previous.getSolution()); } /** * Represents a solution (x, y) to a linear Diophantine equation. * <p> * Special instances: * <ul> * <li>{@link #NO_SOLUTION} - indicates no integer solutions exist</li> * <li>{@link #INFINITE_SOLUTIONS} - indicates infinitely many solutions * exist</li> * </ul> * </p> */ public static final class Solution { /** * Singleton instance representing the case where no solution exists. */ public static final Solution NO_SOLUTION = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE); /** * Singleton instance representing the case where infinite solutions exist. */ public static final Solution INFINITE_SOLUTIONS = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE); private int x; private int y; /** * Constructs a solution with the given x and y values. * * @param x the x coordinate of the solution * @param y the y coordinate of the solution */ public Solution(int x, int y) { this.x = x; this.y = y; } /** * Gets the x value of this solution. * * @return the x value */ public int getX() { return x; } /** * Gets the y value of this solution. * * @return the y value */ public int getY() { return y; } /** * Sets the x value of this solution. * * @param x the new x value */ public void setX(int x) { this.x = x; } /** * Sets the y value of this solution. * * @param y the new y value */ public void setY(int y) { this.y = y; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } var that = (Solution) obj; return this.x == that.x && this.y == that.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public String toString() { return "Solution[" + "x=" + x + ", " + "y=" + y + ']'; } } /** * Represents a linear Diophantine equation of the form ax + by = c. * * @param a the coefficient of x * @param b the coefficient of y * @param c the constant term */ public record Equation(int a, int b, int c) { } /** * A wrapper class that holds both the GCD and the solution coefficients * from the Extended Euclidean Algorithm. * <p> * This class is used internally to pass results between recursive calls * of the GCD computation. * </p> */ public static final class GcdSolutionWrapper { private int gcd; private Solution solution; /** * Constructs a GcdSolutionWrapper with the given GCD and solution. * * @param gcd the greatest common divisor * @param solution the solution coefficients */ public GcdSolutionWrapper(int gcd, Solution solution) { this.gcd = gcd; this.solution = solution; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj == null || obj.getClass() != this.getClass()) { return false; } var that = (GcdSolutionWrapper) obj; return (this.gcd == that.gcd && Objects.equals(this.solution, that.solution)); } /** * Gets the GCD value. * * @return the GCD */ public int getGcd() { return gcd; } /** * Sets the GCD value. * * @param gcd the new GCD value */ public void setGcd(int gcd) { this.gcd = gcd; } /** * Gets the solution coefficients. * * @return the solution */ public Solution getSolution() { return solution; } /** * Sets the solution coefficients. * * @param solution the new solution */ public void setSolution(Solution solution) { this.solution = solution; } @Override public int hashCode() { return Objects.hash(gcd, solution); } @Override public String toString() { return ("GcdSolutionWrapper[" + "gcd=" + gcd + ", " + "solution=" + solution + ']'); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AbsoluteMax.java
src/main/java/com/thealgorithms/maths/AbsoluteMax.java
package com.thealgorithms.maths; public final class AbsoluteMax { private AbsoluteMax() { } /** * Finds the absolute maximum value among the given numbers. * * @param numbers The numbers to compare. * @return The absolute maximum value. * @throws IllegalArgumentException If the input array is empty or null. */ public static int getMaxValue(int... numbers) { if (numbers == null || numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty or null"); } int absMax = numbers[0]; for (int i = 1; i < numbers.length; i++) { if (Math.abs(numbers[i]) > Math.abs(absMax) || (Math.abs(numbers[i]) == Math.abs(absMax) && numbers[i] > absMax)) { absMax = numbers[i]; } } return absMax; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Armstrong.java
src/main/java/com/thealgorithms/maths/Armstrong.java
package com.thealgorithms.maths; /** * This class checks whether a given number is an Armstrong number or not. * An Armstrong number is a number that is equal to the sum of its own digits, * each raised to the power of the number of digits. * * For example, 370 is an Armstrong number because 3^3 + 7^3 + 0^3 = 370. * 1634 is an Armstrong number because 1^4 + 6^4 + 3^4 + 4^4 = 1634. * An Armstrong number is often called a Narcissistic number. * * @author satyabarghav * @modifier rahul katteda - (13/01/2025) - [updated the logic for getting total number of digits] */ public class Armstrong { /** * Checks whether a given number is an Armstrong number or not. * * @param number the number to check * @return {@code true} if the given number is an Armstrong number, {@code false} otherwise */ public boolean isArmstrong(int number) { if (number < 0) { return false; // Negative numbers cannot be Armstrong numbers } long sum = 0; int totalDigits = (int) Math.log10(number) + 1; // get the length of the number (number of digits) long originalNumber = number; while (originalNumber > 0) { long digit = originalNumber % 10; sum += (long) Math.pow(digit, totalDigits); // The digit raised to the power of total number of digits and added to the sum. originalNumber /= 10; } return sum == number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/SquareFreeInteger.java
src/main/java/com/thealgorithms/maths/Prime/SquareFreeInteger.java
package com.thealgorithms.maths.Prime; /* * Java program for Square free integer * This class has a function which checks * if an integer has repeated prime factors * and will return false if the number has repeated prime factors. * true otherwise * Wikipedia: https://en.wikipedia.org/wiki/Square-free_integer * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ import java.util.HashSet; import java.util.List; public final class SquareFreeInteger { private SquareFreeInteger() { } /** * This method returns whether an integer is square free * * @param number Integer value which is to be checked * @return false when number has repeated prime factors * true when number has non repeated prime factors * @throws IllegalArgumentException when number is negative or zero */ public static boolean isSquareFreeInteger(int number) { if (number <= 0) { // throw exception when number is less than or is zero throw new IllegalArgumentException("Number must be greater than zero."); } // Store prime factors of number which is passed as argument // in a list List<Integer> primeFactorsList = PrimeFactorization.pfactors(number); // Create set from list of prime factors of integer number // if size of list and set is equal then the argument passed to this method is square free // if size of list and set is not equal then the argument passed to this method is not // square free return primeFactorsList.size() == new HashSet<>(primeFactorsList).size(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/LiouvilleLambdaFunction.java
src/main/java/com/thealgorithms/maths/Prime/LiouvilleLambdaFunction.java
package com.thealgorithms.maths.Prime; /* * Java program for liouville lambda function * For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity. * It has values in {−1, 1} depending on the factorization of n into prime factors: * λ(n) = +1 if n is a positive integer with an even number of prime factors. * λ(n) = −1 if n is a positive integer with an odd number of prime factors. * Wikipedia: https://en.wikipedia.org/wiki/Liouville_function * * Author: Akshay Dubey (https://github.com/itsAkshayDubey) * * */ public final class LiouvilleLambdaFunction { private LiouvilleLambdaFunction() { } /** * This method returns λ(n) of given number n * * @param number Integer value which λ(n) is to be calculated * @return 1 when number has even number of prime factors * -1 when number has odd number of prime factors * @throws IllegalArgumentException when number is negative */ public static int liouvilleLambda(int number) { if (number <= 0) { // throw exception when number is less than or is zero throw new IllegalArgumentException("Number must be greater than zero."); } // return 1 if size of prime factor list is even, -1 otherwise return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Prime/PrimeFactorization.java
src/main/java/com/thealgorithms/maths/Prime/PrimeFactorization.java
package com.thealgorithms.maths.Prime; /* * Authors: * (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi) * (2) Akshay Dubey (https://github.com/itsAkshayDubey) */ import java.util.ArrayList; import java.util.List; public final class PrimeFactorization { private PrimeFactorization() { } public static List<Integer> pfactors(int n) { List<Integer> primeFactors = new ArrayList<>(); if (n == 0) { return primeFactors; } while (n % 2 == 0) { primeFactors.add(2); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { primeFactors.add(i); n /= i; } } if (n > 2) { primeFactors.add(n); } return primeFactors; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false