Format code with prettier (#3375)

This commit is contained in:
acbin
2022-10-03 17:23:00 +08:00
committed by GitHub
parent 32b9b11ed5
commit e96f567bfc
464 changed files with 11483 additions and 6189 deletions

View File

@ -1,7 +1,6 @@
package com.thealgorithms.maths;
public record ADTFraction(int numerator, int denominator) {
/**
* Initializes a newly created {@code ADTFraction} object so that it represents
* a fraction with the {@code numerator} and {@code denominator} provided as arguments.
@ -22,10 +21,13 @@ public record ADTFraction(int numerator, int denominator) {
* @return A new {@code ADTFraction} containing the result of the operation
*/
public ADTFraction plus(ADTFraction fraction) {
var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator;
var numerator =
this.denominator *
fraction.numerator +
this.numerator *
fraction.denominator;
var denominator = this.denominator * fraction.denominator;
return new ADTFraction(numerator, denominator);
}
/**

View File

@ -19,10 +19,11 @@ public class AbsoluteMax {
int value = numbers[0];
};
Arrays.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
.forEach(number -> absMaxWrapper.value = number);
Arrays
.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) > Math.abs(absMaxWrapper.value))
.forEach(number -> absMaxWrapper.value = number);
return absMaxWrapper.value;
}

View File

@ -19,10 +19,11 @@ public class AbsoluteMin {
int value = numbers[0];
};
Arrays.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
.forEach(number -> absMinWrapper.value = number);
Arrays
.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
.forEach(number -> absMinWrapper.value = number);
return absMinWrapper.value;
}

View File

@ -22,10 +22,11 @@ public class AliquotSum {
int value = 0;
};
IntStream.iterate(1, i -> ++i)
.limit(number / 2)
.filter(i -> number % i == 0)
.forEach(i -> sumWrapper.value += i);
IntStream
.iterate(1, i -> ++i)
.limit(number / 2)
.filter(i -> number % i == 0)
.forEach(i -> sumWrapper.value += i);
return sumWrapper.value;
}

View File

@ -20,7 +20,6 @@ package com.thealgorithms.maths;
public class AmicableNumber {
public static void main(String[] args) {
AmicableNumber.findAllInRange(1, 3000);
/* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284) 2: = ( 1184,1210)
3: = ( 2620,2924) So it worked */
@ -33,10 +32,9 @@ public class AmicableNumber {
* @return
*/
static void findAllInRange(int startValue, int stopValue) {
/* the 2 for loops are to avoid to double check tuple. For example (200,100) and (100,200) is the same calculation
* also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
* */
* also to avoid is to check the number with it self. a number with itself is always a AmicableNumber
* */
StringBuilder res = new StringBuilder();
int countofRes = 0;
@ -44,19 +42,22 @@ public class AmicableNumber {
for (int j = i + 1; j <= stopValue; j++) {
if (isAmicableNumber(i, j)) {
countofRes++;
res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
res.append(
"" + countofRes + ": = ( " + i + "," + j + ")" + "\t"
);
}
}
}
res.insert(
0,
"Int Range of "
+ startValue
+ " till "
+ stopValue
+ " there are "
+ countofRes
+ " Amicable_numbers.These are \n ");
0,
"Int Range of " +
startValue +
" till " +
stopValue +
" there are " +
countofRes +
" Amicable_numbers.These are \n "
);
System.out.println(res.toString());
}
@ -68,9 +69,12 @@ public class AmicableNumber {
* otherwise false
*/
static boolean isAmicableNumber(int numberOne, int numberTwo) {
return ((recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo
&& numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)));
return (
(
recursiveCalcOfDividerSum(numberOne, numberOne) == numberTwo &&
numberOne == recursiveCalcOfDividerSum(numberTwo, numberTwo)
)
);
}
/**
@ -81,7 +85,6 @@ public class AmicableNumber {
* @return sum of all the dividers
*/
static int recursiveCalcOfDividerSum(int number, int div) {
if (div == 1) {
return 0;
} else if (number % --div == 0) {

View File

@ -6,7 +6,6 @@ package com.thealgorithms.maths;
public class Area {
public static void main(String[] args) {
/* test cube */
assert Double.compare(surfaceAreaCube(1), 6.0) == 0;
@ -33,16 +32,17 @@ public class Area {
assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0;
/* test cylinder */
assert Double.compare(surfaceAreaCylinder(1, 2), 18.84955592153876) == 0;
assert Double.compare(surfaceAreaCylinder(1, 2), 18.84955592153876) ==
0;
/* test hemisphere */
assert Double.compare(surfaceAreaHemisphere(5), 235.61944901923448) == 0;
assert Double.compare(surfaceAreaHemisphere(5), 235.61944901923448) ==
0;
assert Double.compare(surfaceAreaHemisphere(1), 9.42477796076938) == 0;
/* test cone */
assert Double.compare(surfaceAreaCone(6, 8), 301.59289474462014) == 0;
assert Double.compare(surfaceAreaCone(10, 24), 1130.9733552923256) == 0;
}
/**
@ -127,7 +127,11 @@ public class Area {
* @param height height of trapezium
* @return area of given trapezium
*/
private static double surfaceAreaTrapezium(double base1, double base2, double height) {
private static double surfaceAreaTrapezium(
double base1,
double base2,
double height
) {
return (base1 + base2) * height / 2;
}
@ -159,6 +163,10 @@ public class Area {
* @return surface area of given cone.
*/
private static double surfaceAreaCone(double radius, double height) {
return Math.PI * radius * (radius + Math.pow((height * height + radius * radius), 0.5));
return (
Math.PI *
radius *
(radius + Math.pow((height * height + radius * radius), 0.5))
);
}
}

View File

@ -26,4 +26,4 @@ public class Armstrong {
}
return sum == number;
}
}
}

View File

@ -30,8 +30,7 @@ public class AutomorphicNumber {
} while (n != 0);
s = Math.pow(10, c);
r = p % (int) s;
if (m == r) //Checking if the original number entered is present at the end of the square
{
if (m == r) { //Checking if the original number entered is present at the end of the square
return true;
} else {
return false;
@ -44,7 +43,9 @@ public class AutomorphicNumber {
* Number: 7 Output - It is not an Automorphic Number.
*/
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println("Enter a Number: ");
int n = Integer.parseInt(br.readLine());
if (isAutomorphic(n)) {

View File

@ -8,10 +8,19 @@ public class Average {
private static final double SMALL_VALUE = 0.00001f;
public static void main(String[] args) {
assert Math.abs(average(new double[]{3, 6, 9, 12, 15, 18, 21}) - 12) < SMALL_VALUE;
assert Math.abs(average(new double[]{5, 10, 15, 20, 25, 30, 35}) - 20) < SMALL_VALUE;
assert Math.abs(average(new double[]{1, 2, 3, 4, 5, 6, 7, 8}) - 4.5) < SMALL_VALUE;
int[] array = {2, 4, 10};
assert Math.abs(
average(new double[] { 3, 6, 9, 12, 15, 18, 21 }) - 12
) <
SMALL_VALUE;
assert Math.abs(
average(new double[] { 5, 10, 15, 20, 25, 30, 35 }) - 20
) <
SMALL_VALUE;
assert Math.abs(
average(new double[] { 1, 2, 3, 4, 5, 6, 7, 8 }) - 4.5
) <
SMALL_VALUE;
int[] array = { 2, 4, 10 };
assert average(array) == 5;
}

View File

@ -5,9 +5,9 @@ package com.thealgorithms.maths;
* Binomial Cofficients: A binomial cofficient 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 class BinomialCoefficient {
@ -20,8 +20,10 @@ public class BinomialCoefficient {
* @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) {
public static int binomialCoefficient(
int totalObjects,
int numberOfObjects
) {
// Base Case
if (numberOfObjects > totalObjects) {
return 0;
@ -33,7 +35,9 @@ public class BinomialCoefficient {
}
// Recursive Call
return binomialCoefficient(totalObjects - 1, numberOfObjects - 1)
+ binomialCoefficient(totalObjects - 1, numberOfObjects);
return (
binomialCoefficient(totalObjects - 1, numberOfObjects - 1) +
binomialCoefficient(totalObjects - 1, numberOfObjects)
);
}
}

View File

@ -39,10 +39,10 @@ public class CircularConvolutionFFT {
* @return The convolved signal.
*/
public static ArrayList<FFT.Complex> fftCircularConvolution(
ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
int convolvedSize
= Math.max(
a.size(), b.size()); // The two signals must have the same size equal to the bigger one
ArrayList<FFT.Complex> a,
ArrayList<FFT.Complex> b
) {
int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one
padding(a, convolvedSize); // Zero padding the smaller signal
padding(b, convolvedSize);

View File

@ -43,7 +43,9 @@ public class ConvolutionFFT {
* @return The convolved signal.
*/
public static ArrayList<FFT.Complex> convolutionFFT(
ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) {
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);
@ -57,9 +59,7 @@ public class ConvolutionFFT {
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
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;

View File

@ -2,9 +2,9 @@ package com.thealgorithms.maths;
import java.util.*;
/*
* @author Ojasva Jain
* Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant
/*
* @author Ojasva Jain
* Determinant of Matrix Wikipedia link : https://en.wikipedia.org/wiki/Determinant
*/
public class DeterminantOfMatrix {

View File

@ -39,8 +39,7 @@ package com.thealgorithms.maths;
class 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
{
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));
@ -49,17 +48,15 @@ class DigitalRoot {
// This function is used for finding the sum of digits of number
public static int single(int n) {
if (n <= 9) // if n becomes less than 10 than return 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
return (n % 10) + single(n / 10); // n % 10 for extracting digits one by one
}
} // n / 10 is the number obtainded after removing the digit one by one
} // n / 10 is the number obtainded after removing the digit one by one
// Sum of digits is stored in the Stack memory and then finally returned
}
/**
* Time Complexity : O((Number of Digits)^2) Auxiliary Space Complexity :
* O(Number of Digits) Constraints : 1 <= n <= 10^7

View File

@ -1,46 +1,57 @@
package com.thealgorithms.maths;
public class 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);
double d = Math.sqrt(dX + dY);
return d;
}
public static double manhattanDistance(double x1, double y1, double x2, double y2) {
double d = Math.abs(x1 - x2) + Math.abs(y1 - y2);
return d;
}
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);
double d = Math.sqrt(dX + dY);
return d;
}
public static int hammingDistance(int[] b1, int[] b2) {
int d = 0;
public static double manhattanDistance(
double x1,
double y1,
double x2,
double y2
) {
double d = Math.abs(x1 - x2) + Math.abs(y1 - y2);
return d;
}
if (b1.length != b2.length) {
return -1; // error, both array must be have the same length
}
public static int hammingDistance(int[] b1, int[] b2) {
int d = 0;
for (int i = 0; i < b1.length; i++) {
d += Math.abs(b1[i] - b2[i]);
}
if (b1.length != b2.length) {
return -1; // error, both array must be have the same length
}
return d;
}
for (int i = 0; i < b1.length; i++) {
d += Math.abs(b1[i] - b2[i]);
}
public static double minkowskiDistance(double[] p1, double[] p2, int p) {
double d = 0;
double distance = 0.0;
return d;
}
if (p1.length != p2.length) {
return -1; // error, both array must be have the same length
}
public static double minkowskiDistance(double[] p1, double[] p2, int p) {
double d = 0;
double distance = 0.0;
for (int i = 0; i < p1.length; i++) {
distance += Math.abs(Math.pow(p1[i] - p2[i], p));
}
if (p1.length != p2.length) {
return -1; // error, both array must be have the same length
}
distance = Math.pow(distance, (double) 1 / p);
d = distance;
return d;
}
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;
}
}

View File

@ -18,11 +18,10 @@ public class DudeneyNumber {
if (cube_root * cube_root * cube_root != n) {
return false;
}
int sum_of_digits = 0;// Stores the sums of the digit of the entered number
int temp = n;//A temporary variable to store the entered number
int sum_of_digits = 0; // Stores the sums of the digit of the entered number
int temp = n; //A temporary variable to store the entered number
// Loop to calculate sum of the digits.
while (temp > 0) {
// Extracting Last digit of the number
int rem = temp % 10;
@ -33,7 +32,7 @@ public class DudeneyNumber {
temp /= 10;
}
//If the cube root of the number is not equal to the sum of its digits we return false.
//If the cube root of the number is not equal to the sum of its digits we return false.
if (cube_root != sum_of_digits) {
return false;
}
@ -47,7 +46,9 @@ public class DudeneyNumber {
* 125 Output - It is not a Dudeney Number.
*/
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println("Enter a Number: ");
int n = Integer.parseInt(br.readLine());
if (isDudeney(n)) {

View File

@ -26,24 +26,40 @@ public class EulerMethod {
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.println(String.format("x: %1$f; y: %2$f", point[0], point[1])));
points1.forEach(point ->
System.out.println(
String.format("x: %1$f; y: %2$f", 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.println(String.format("x: %1$f; y: %2$f", point[0], point[1])));
points2.forEach(point ->
System.out.println(
String.format("x: %1$f; y: %2$f", 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);
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.println(String.format("x: %1$f; y: %2$f", point[0], point[1])));
points3.forEach(point ->
System.out.println(
String.format("x: %1$f; y: %2$f", point[0], point[1])
)
);
}
/**
@ -57,14 +73,20 @@ public class EulerMethod {
* @return The next y-value.
*/
public static double eulerStep(
double xCurrent,
double stepSize,
double yCurrent,
BiFunction<Double, Double, Double> differentialEquation) {
double xCurrent,
double stepSize,
double yCurrent,
BiFunction<Double, Double, Double> differentialEquation
) {
if (stepSize <= 0) {
throw new IllegalArgumentException("stepSize should be greater than zero");
throw new IllegalArgumentException(
"stepSize should be greater than zero"
);
}
double yNext = yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent);
double yNext =
yCurrent +
stepSize *
differentialEquation.apply(xCurrent, yCurrent);
return yNext;
}
@ -81,29 +103,35 @@ public class EulerMethod {
* equation.
*/
public static ArrayList<double[]> eulerFull(
double xStart,
double xEnd,
double stepSize,
double yStart,
BiFunction<Double, Double, Double> differentialEquation) {
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");
throw new IllegalArgumentException(
"xEnd should be greater than xStart"
);
}
if (stepSize <= 0) {
throw new IllegalArgumentException("stepSize should be greater than zero");
throw new IllegalArgumentException(
"stepSize should be greater than zero"
);
}
ArrayList<double[]> points = new ArrayList<double[]>();
double[] firstPoint = {xStart, yStart};
double[] firstPoint = { xStart, yStart };
points.add(firstPoint);
double yCurrent = yStart;
double xCurrent = xStart;
while (xCurrent < xEnd) {
// Euler method for next step
yCurrent = eulerStep(xCurrent, stepSize, yCurrent, differentialEquation);
yCurrent =
eulerStep(xCurrent, stepSize, yCurrent, differentialEquation);
xCurrent += stepSize;
double[] point = {xCurrent, yCurrent};
double[] point = { xCurrent, yCurrent };
points.add(point);
}

View File

@ -143,7 +143,7 @@ public class FFT {
public Complex divide(Complex z) {
Complex temp = new Complex();
double d = z.abs() * z.abs();
d = (double)Math.round(d * 1000000000d) / 1000000000d;
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;
@ -180,12 +180,15 @@ public class FFT {
* @param inverse True if you want to find the inverse FFT.
* @return
*/
public static ArrayList<Complex> fft(ArrayList<Complex> x, boolean inverse) {
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);
x = fftBitReversal(N, log2N, x);
int direction = inverse ? -1 : 1;
/* Main loop of the algorithm */
@ -203,12 +206,12 @@ public class FFT {
}
}
}
x = inverseFFT(N,inverse,x);
x = inverseFFT(N, inverse, x);
return x;
}
/* Find the log2(N) */
public static int findLog2(int N){
public static int findLog2(int N) {
int log2N = 0;
while ((1 << log2N) < N) {
log2N++;
@ -217,7 +220,11 @@ public class FFT {
}
/* Swap the values of the signal with bit-reversal method */
public static ArrayList<Complex> fftBitReversal(int N, int log2N, ArrayList<Complex> x){
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);
@ -229,7 +236,11 @@ public class FFT {
}
/* Divide by N if we want the inverse FFT */
public static ArrayList<Complex> inverseFFT(int N, boolean inverse, ArrayList<Complex> x ){
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);

View File

@ -38,16 +38,26 @@ public class FFTBluestein {
for (int i = 0; i < N; i++) {
double angle = (i - N + 1) * (i - N + 1) * Math.PI / N * direction;
bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle)));
bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle)));
bn.set(
bnSize - i - 1,
new FFT.Complex(Math.cos(angle), Math.sin(angle))
);
}
/* Initialization of the a(n) sequence */
for (int i = 0; i < N; i++) {
double angle = -i * i * Math.PI / N * direction;
an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle))));
an.add(
x
.get(i)
.multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))
);
}
ArrayList<FFT.Complex> convolution = ConvolutionFFT.convolutionFFT(an, bn);
ArrayList<FFT.Complex> convolution = ConvolutionFFT.convolutionFFT(
an,
bn
);
/* The final multiplication of the convolution with the b*(k) factor */
for (int i = 0; i < N; i++) {

View File

@ -21,8 +21,7 @@ public class Factorial {
throw new IllegalArgumentException("number is negative");
}
long factorial = 1;
for (int i = 1; i <= n; factorial *= i, ++i)
;
for (int i = 1; i <= n; factorial *= i, ++i);
return factorial;
}
}

View File

@ -2,15 +2,14 @@
* Github : https://github.com/siddhant2002
*/
/** Program description - To find out the inverse square root of the given number*/
/** Wikipedia Link - https://en.wikipedia.org/wiki/Fast_inverse_square_root */
package com.thealgorithms.maths;
public class FastInverseSqrt {
public static boolean inverseSqrt(float number) {
float x = number;
float xhalf = 0.5f * x;
@ -18,15 +17,14 @@ public class FastInverseSqrt {
i = 0x5f3759df - (i >> 1);
x = Float.intBitsToFloat(i);
x = x * (1.5f - xhalf * x * x);
return x == (float)((float)1/(float)Math.sqrt(number));
return x == (float) ((float) 1 / (float) Math.sqrt(number));
}
/**
* 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
*/
public static boolean inverseSqrt(double number) {
double x = number;
double xhalf = 0.5d * x;
@ -37,23 +35,21 @@ public class FastInverseSqrt {
x = x * (1.5d - xhalf * x * x);
}
x *= number;
return x == 1/Math.sqrt(number);
return x == 1 / 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
*/
}
/**
* 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)
*/
* 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)
*/

View File

@ -25,28 +25,31 @@ public class FibonacciJavaStreams {
return Optional.of(BigDecimal.ONE);
}
final List<BigDecimal> results = Stream.iterate(
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
)
.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
);
(list1, list2) -> list1
);
return results.isEmpty()
? Optional.empty()
: Optional.of(results.get(results.size() - 1));
? Optional.empty()
: Optional.of(results.get(results.size() - 1));
}
public static void assertThat(final Object actual, final Object expected) {
if (!Objects.equals(actual, expected)) {
throw new AssertionError(String.format("expected=%s but was actual=%s", expected, actual));
throw new AssertionError(
String.format("expected=%s but was actual=%s", expected, actual)
);
}
}
@ -88,27 +91,39 @@ public class FibonacciJavaStreams {
{
final Optional<BigDecimal> result = calculate(new BigDecimal(30));
assertThat(result.isPresent(), true);
result.ifPresent(value -> assertThat(value, new BigDecimal(832040)));
result.ifPresent(value -> assertThat(value, new BigDecimal(832040))
);
}
{
final Optional<BigDecimal> result = calculate(new BigDecimal(40));
assertThat(result.isPresent(), true);
result.ifPresent(value -> assertThat(value, new BigDecimal(102334155)));
result.ifPresent(value ->
assertThat(value, new BigDecimal(102334155))
);
}
{
final Optional<BigDecimal> result = calculate(new BigDecimal(50));
assertThat(result.isPresent(), true);
result.ifPresent(value -> assertThat(value, new BigDecimal(12586269025L)));
result.ifPresent(value ->
assertThat(value, new BigDecimal(12586269025L))
);
}
{
final Optional<BigDecimal> result = calculate(new BigDecimal(100));
assertThat(result.isPresent(), true);
result.ifPresent(value -> assertThat(value, new BigDecimal("354224848179261915075")));
result.ifPresent(value ->
assertThat(value, new BigDecimal("354224848179261915075"))
);
}
{
final Optional<BigDecimal> result = calculate(new BigDecimal(200));
assertThat(result.isPresent(), true);
result.ifPresent(value -> assertThat(value, new BigDecimal("280571172992510140037611932413038677189525")));
result.ifPresent(value ->
assertThat(
value,
new BigDecimal("280571172992510140037611932413038677189525")
)
);
}
}
}

View File

@ -35,6 +35,9 @@ public class FibonacciNumber {
* @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification
*/
public static boolean isFibonacciNumber(int number) {
return isPerfectSquare(5 * number * number + 4) || isPerfectSquare(5 * number * number - 4);
return (
isPerfectSquare(5 * number * number + 4) ||
isPerfectSquare(5 * number * number - 4)
);
}
}

View File

@ -7,6 +7,7 @@ import java.util.Random;
* use quick sort algorithm to get kth largest or kth smallest element in given array
*/
public class FindKthNumber {
private static final Random random = new Random();
public static void main(String[] args) {

View File

@ -17,8 +17,10 @@ public class FindMaxRecursion {
array[i] = rand.nextInt() % 100;
}
assert max(array, array.length) == Arrays.stream(array).max().getAsInt();
assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt();
assert max(array, array.length) ==
Arrays.stream(array).max().getAsInt();
assert max(array, 0, array.length - 1) ==
Arrays.stream(array).max().getAsInt();
}
/**
@ -50,6 +52,8 @@ public class FindMaxRecursion {
* @return max value of {@code array}
*/
public static int max(int[] array, int len) {
return len == 1 ? array[0] : Math.max(max(array, len - 1), array[len - 1]);
return len == 1
? array[0]
: Math.max(max(array, len - 1), array[len - 1]);
}
}

View File

@ -20,8 +20,10 @@ public class FindMinRecursion {
array[i] = rand.nextInt() % 100;
}
assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt();
assert min(array, array.length) == Arrays.stream(array).min().getAsInt();
assert min(array, 0, array.length - 1) ==
Arrays.stream(array).min().getAsInt();
assert min(array, array.length) ==
Arrays.stream(array).min().getAsInt();
}
/**
@ -53,6 +55,8 @@ public class FindMinRecursion {
* @return min value of {@code array}
*/
public static int min(int[] array, int len) {
return len == 1 ? array[0] : Math.min(min(array, len - 1), array[len - 1]);
return len == 1
? array[0]
: Math.min(min(array, len - 1), array[len - 1]);
}
}

View File

@ -40,8 +40,7 @@ public class GCD {
*/
public static int gcd(int[] number) {
int result = number[0];
for (int i = 1; i < number.length; i++) // call gcd function (input two value)
{
for (int i = 1; i < number.length; i++) { // call gcd function (input two value)
result = gcd(result, number[i]);
}
@ -49,10 +48,14 @@ public class GCD {
}
public static void main(String[] args) {
int[] myIntArray = {4, 16, 32};
int[] myIntArray = { 4, 16, 32 };
// call gcd function (input array)
System.out.println(gcd(myIntArray)); // => 4
System.out.printf("gcd(40,24)=%d gcd(24,40)=%d%n", gcd(40, 24), gcd(24, 40)); // => 8
System.out.printf(
"gcd(40,24)=%d gcd(24,40)=%d%n",
gcd(40, 24),
gcd(24, 40)
); // => 8
}
}

View File

@ -22,7 +22,6 @@ public class GCDRecursion {
* @return gcd
*/
public static int gcd(int a, int b) {
if (a < 0 || b < 0) {
throw new ArithmeticException();
}

View File

@ -4,7 +4,10 @@ import java.util.ArrayList;
public class Gaussian {
public static ArrayList<Double> gaussian(int mat_size, ArrayList<Double> matrix) {
public static ArrayList<Double> gaussian(
int mat_size,
ArrayList<Double> matrix
) {
ArrayList<Double> answerArray = new ArrayList<Double>();
int i, j = 0;
@ -24,7 +27,11 @@ public class Gaussian {
}
// Perform Gaussian elimination
public static double[][] gaussianElimination(int mat_size, int i, double[][] mat) {
public static double[][] gaussianElimination(
int mat_size,
int i,
double[][] mat
) {
int step = 0;
for (step = 0; step < mat_size - 1; step++) {
for (i = step; i < mat_size - 1; i++) {
@ -39,7 +46,11 @@ public class Gaussian {
}
// calculate the x_1, x_2,... values of the gaussian and save it in an arraylist.
public static ArrayList<Double> valueOfGaussian(int mat_size, double[][] x, double[][] mat) {
public static ArrayList<Double> valueOfGaussian(
int mat_size,
double[][] x,
double[][] mat
) {
ArrayList<Double> answerArray = new ArrayList<Double>();
int i, j;
@ -64,4 +75,4 @@ public class Gaussian {
}
return answerArray;
}
}
}

View File

@ -19,7 +19,6 @@ public class HarshadNumber {
* @param a The number which should be checked
*/
public static void checkHarshadNumber(long a) {
long b = a;
int sum = 0;

View File

@ -5,15 +5,14 @@ package com.thealgorithms.maths;
*/
public class HeronsFormula {
public static double Herons(int s1, int s2, int s3)
{
double a = s1;
double b = s2;
double c = s3;
double s = (a + b + c)/2.0;
double area = 0;
area = Math.sqrt((s)*(s-a)*(s-b)*(s-c));
return area;
}
public static double Herons(int s1, int s2, int s3) {
double a = s1;
double b = s2;
double c = s3;
double s = (a + b + c) / 2.0;
double area = 0;
area = Math.sqrt((s) * (s - a) * (s - b) * (s - c));
return area;
}
}

View File

@ -1,36 +1,36 @@
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 class 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;
}
}
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 class 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;
}
}

View File

@ -4,14 +4,15 @@ import java.util.ArrayList;
import java.util.List;
/*
* Java program for printing juggler sequence
* Java program for printing juggler sequence
* Wikipedia: https://en.wikipedia.org/wiki/Juggler_sequence
*
*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
*
*
* */
public class JugglerSequence {
/**
* This method prints juggler sequence starting with the number in the parameter
*
@ -34,7 +35,10 @@ public class JugglerSequence {
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));
temp =
(int) Math.floor(
Math.sqrt(n) * Math.sqrt(n) * Math.sqrt(n)
);
}
n = temp;
seq.add(n + "");

View File

@ -1,53 +1,68 @@
package com.thealgorithms.maths;
import java.math.BigInteger;
import java.util.*;
public class KaprekarNumbers {
/* This program demonstrates if a given number is Kaprekar Number or not.
/* This program demonstrates if a given number is Kaprekar Number or not.
Kaprekar Number: A Kaprekar number is an n-digit number which its square can be split into two parts where the right part has n
digits and sum of these parts is equal to the original number. */
// Provides a list of kaprekarNumber in a range
public static ArrayList<Long> kaprekarNumberInRange(long start, long end) throws Exception {
long n = end-start;
if (n <0) throw new Exception("Invalid range");
ArrayList<Long> list = new ArrayList<>();
// Provides a list of kaprekarNumber in a range
public static ArrayList<Long> kaprekarNumberInRange(long start, long end)
throws Exception {
long n = end - start;
if (n < 0) throw new Exception("Invalid range");
ArrayList<Long> list = new ArrayList<>();
for (long i = start; i <= end; i++) {
if (isKaprekarNumber(i)) list.add(i);
}
for (long i = start; i <= end; i++) {
if (isKaprekarNumber(i)) list.add(i);
}
return list;
}
// Checks whether a given number is Kaprekar Number or not
public static boolean isKaprekarNumber(long num) {
String number = Long.toString(num);
BigInteger originalNumber = new BigInteger(number);
BigInteger numberSquared = originalNumber.multiply(originalNumber);
if(number.length() == numberSquared.toString().length()){
return number.equals(numberSquared.toString());
}
else{
BigInteger leftDigits1 = new BigInteger("0");
BigInteger leftDigits2;
if(numberSquared.toString().contains("0")){
leftDigits1 = new BigInteger(
numberSquared.toString().
substring(0, numberSquared.toString().indexOf("0")
)
);
}
leftDigits2 = new BigInteger(
numberSquared.toString()
.substring(0, (numberSquared.toString().length() - number.length()))
);
BigInteger rightDigits = new BigInteger(numberSquared.toString().substring(numberSquared.toString().length() - number.length()));
String x = leftDigits1.add(rightDigits).toString();
String y = leftDigits2.add(rightDigits).toString();
return (number.equals(x)) || (number.equals(y));
}
}
return list;
}
// Checks whether a given number is Kaprekar Number or not
public static boolean isKaprekarNumber(long num) {
String number = Long.toString(num);
BigInteger originalNumber = new BigInteger(number);
BigInteger numberSquared = originalNumber.multiply(originalNumber);
if (number.length() == numberSquared.toString().length()) {
return number.equals(numberSquared.toString());
} else {
BigInteger leftDigits1 = new BigInteger("0");
BigInteger leftDigits2;
if (numberSquared.toString().contains("0")) {
leftDigits1 =
new BigInteger(
numberSquared
.toString()
.substring(0, numberSquared.toString().indexOf("0"))
);
}
leftDigits2 =
new BigInteger(
numberSquared
.toString()
.substring(
0,
(
numberSquared.toString().length() -
number.length()
)
)
);
BigInteger rightDigits = new BigInteger(
numberSquared
.toString()
.substring(
numberSquared.toString().length() - number.length()
)
);
String x = leftDigits1.add(rightDigits).toString();
String y = leftDigits2.add(rightDigits).toString();
return (number.equals(x)) || (number.equals(y));
}
}
}

View File

@ -4,42 +4,42 @@ import java.util.*;
class KeithNumber {
//user-defined function that checks if the given number is Keith or not
//user-defined function that checks if the given number is Keith or not
static boolean isKeith(int x) {
//List stores all the digits of the X
//List stores all the digits of the X
ArrayList<Integer> terms = new ArrayList<Integer>();
//n denotes the number of digits
//n denotes the number of digits
int temp = x, n = 0;
//executes until the condition becomes false
//executes until the condition becomes false
while (temp > 0) {
//determines the last digit of the number and add it to the List
//determines the last digit of the number and add it to the List
terms.add(temp % 10);
//removes the last digit
//removes the last digit
temp = temp / 10;
//increments the number of digits (n) by 1
//increments the number of digits (n) by 1
n++;
}
//reverse the List
//reverse the List
Collections.reverse(terms);
int next_term = 0, i = n;
//finds next term for the series
//loop executes until the condition returns true
//finds next term for the series
//loop executes until the condition returns true
while (next_term < x) {
next_term = 0;
//next term is the sum of previous n terms (it depends on number of digits the number has)
//next term is the sum of previous n terms (it depends on number of digits the number has)
for (int j = 1; j <= n; j++) {
next_term = next_term + terms.get(i - j);
}
terms.add(next_term);
i++;
}
//when the control comes out of the while loop, there will be two conditions:
//either next_term will be equal to x or greater than x
//if equal, the given number is Keith, else not
//when the control comes out of the while loop, there will be two conditions:
//either next_term will be equal to x or greater than x
//if equal, the given number is Keith, else not
return (next_term == x);
}
//driver code
//driver code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();

View File

@ -8,6 +8,7 @@ Krishnamurthy number is also referred to as a Strong number.
import java.io.*;
public class KrishnamurthyNumber {
//returns True if the number is a Krishnamurthy number and False if it is not.
public static boolean isKMurthy(int n) {
@ -44,8 +45,12 @@ public class KrishnamurthyNumber {
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number to check if it is a Krishnamurthy number: ");
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in)
);
System.out.println(
"Enter a number to check if it is a Krishnamurthy number: "
);
int n = Integer.parseInt(br.readLine());
if (isKMurthy(n)) {
System.out.println(n + " is a Krishnamurthy number.");

View File

@ -1,45 +1,47 @@
package com.thealgorithms.maths;
import java.util.*;
/**
* Is a common mathematics concept to find the smallest value number
* that can be divide using either number without having the remainder.
* 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 class LeastCommonMultiple {
/**
* Driver Code
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner input = new Scanner(System.in);
System.out.println("Please enter first number >> ");
int num1 = input.nextInt();
System.out.println("Please enter second number >> ");
int num2 = input.nextInt();
System.out.println("The least common multiple of two numbers is >> " + lcm(num1,num2));
System.out.println(
"The least common multiple of two numbers is >> " + lcm(num1, num2)
);
}
}
/*
* get least common multiple from two number
*/
public static int lcm (int num1, int num2){
public static int lcm(int num1, int num2) {
int high, num3;
int cmv = 0;
/*
* value selection for the numerator
*/
if (num1 > num2){
if (num1 > num2) {
high = num3 = num1;
}
else{
} else {
high = num3 = num2;
}
while(num1 != 0){
if(high % num1 == 0 && high % num2 == 0){
while (num1 != 0) {
if (high % num1 == 0 && high % num2 == 0) {
cmv = high;
break;
}

View File

@ -16,6 +16,5 @@ public class LeonardoNumber {
for (int i = 0; i < 20; i++) {
System.out.print(leonardoNumber(i) + " ");
}
}
}

View File

@ -27,23 +27,39 @@ public final class LinearDiophantineEquationsSolver {
return toReturn;
}
private static GcdSolutionWrapper gcd(final int a, final int b, final GcdSolutionWrapper previous) {
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 = /* recursive call */ gcd(b, a % b, stubWrapper);
final var next = /* recursive call */gcd(b, a % b, stubWrapper);
previous.getSolution().setX(next.getSolution().getY());
previous.getSolution().setY(next.getSolution().getX() - (a / b) * (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());
}
public static final class Solution {
public static final Solution NO_SOLUTION = new Solution(Integer.MAX_VALUE, Integer.MAX_VALUE);
public static final Solution INFINITE_SOLUTIONS = new Solution(Integer.MIN_VALUE, Integer.MIN_VALUE);
public static final Solution NO_SOLUTION = new Solution(
Integer.MAX_VALUE,
Integer.MAX_VALUE
);
public static final Solution INFINITE_SOLUTIONS = new Solution(
Integer.MIN_VALUE,
Integer.MIN_VALUE
);
private int x;
private int y;
@ -77,8 +93,7 @@ public final class LinearDiophantineEquationsSolver {
return false;
}
var that = (Solution) obj;
return this.x == that.x
&& this.y == that.y;
return this.x == that.x && this.y == that.y;
}
@Override
@ -88,16 +103,11 @@ public final class LinearDiophantineEquationsSolver {
@Override
public String toString() {
return "Solution["
+ "x=" + x + ", "
+ "y=" + y + ']';
return "Solution[" + "x=" + x + ", " + "y=" + y + ']';
}
}
public record Equation(int a, int b, int c) {
}
public record Equation(int a, int b, int c) {}
public static final class GcdSolutionWrapper {
@ -118,8 +128,10 @@ public final class LinearDiophantineEquationsSolver {
return false;
}
var that = (GcdSolutionWrapper) obj;
return this.gcd == that.gcd
&& Objects.equals(this.solution, that.solution);
return (
this.gcd == that.gcd &&
Objects.equals(this.solution, that.solution)
);
}
public int getGcd() {
@ -145,10 +157,15 @@ public final class LinearDiophantineEquationsSolver {
@Override
public String toString() {
return "GcdSolutionWrapper["
+ "gcd=" + gcd + ", "
+ "solution=" + solution + ']';
return (
"GcdSolutionWrapper[" +
"gcd=" +
gcd +
", " +
"solution=" +
solution +
']'
);
}
}
}

View File

@ -2,33 +2,35 @@ package com.thealgorithms.maths;
/*
* Java program for liouville lambda function
* For any positive integer n, define λ(n) as the sum of the primitive nth roots of unity.
* 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 class 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
*/
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.");
}
/**
* 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
*/
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;
}
//return 1 if size of prime factor list is even, -1 otherwise
return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1;
}
}

View File

@ -23,7 +23,9 @@ public class LucasSeries {
* @return nth number of lucas series
*/
public static int lucasSeries(int n) {
return n == 1 ? 2 : n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2);
return n == 1
? 2
: n == 2 ? 1 : lucasSeries(n - 1) + lucasSeries(n - 2);
}
/**

View File

@ -7,7 +7,6 @@ rows, all columns, and both diagonals sum to the same constant. A magic square c
public class MagicSquare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input a number: ");
int num = sc.nextInt();
@ -23,7 +22,10 @@ public class MagicSquare {
magic_square[row_num][col_num] = 1;
for (int i = 2; i <= num * num; i++) {
if (magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] == 0) {
if (
magic_square[(row_num - 1 + num) % num][(col_num + 1) % num] ==
0
) {
row_num = (row_num - 1 + num) % num;
col_num = (col_num + 1) % num;
} else {
@ -45,6 +47,5 @@ public class MagicSquare {
}
System.out.println();
}
}
}

View File

@ -17,20 +17,34 @@ public class MatrixUtil {
return matrix != null && matrix.length > 0 && matrix[0].length > 0;
}
public static boolean hasEqualSizes(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return isValid(matrix1) && isValid(matrix2)
&& matrix1.length == matrix2.length
&& matrix1[0].length == matrix2[0].length;
public static boolean hasEqualSizes(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
return (
isValid(matrix1) &&
isValid(matrix2) &&
matrix1.length == matrix2.length &&
matrix1[0].length == matrix2[0].length
);
}
public static boolean canMultiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return isValid(matrix1) && isValid(matrix2)
&& matrix1[0].length == matrix2.length;
public static boolean canMultiply(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
return (
isValid(matrix1) &&
isValid(matrix2) &&
matrix1[0].length == matrix2.length
);
}
public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2,
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
public static Optional<BigDecimal[][]> operate(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2,
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation
) {
if (!hasEqualSizes(matrix1, matrix2)) {
return Optional.empty();
}
@ -40,26 +54,43 @@ public class MatrixUtil {
final BigDecimal[][] result = new BigDecimal[rowSize][columnSize];
IntStream.range(0, rowSize).forEach(rowIndex
-> IntStream.range(0, columnSize).forEach(columnIndex -> {
final BigDecimal value1 = matrix1[rowIndex][columnIndex];
final BigDecimal value2 = matrix2[rowIndex][columnIndex];
IntStream
.range(0, rowSize)
.forEach(rowIndex ->
IntStream
.range(0, columnSize)
.forEach(columnIndex -> {
final BigDecimal value1 =
matrix1[rowIndex][columnIndex];
final BigDecimal value2 =
matrix2[rowIndex][columnIndex];
result[rowIndex][columnIndex] = operation.apply(value1, value2);
}));
result[rowIndex][columnIndex] =
operation.apply(value1, value2);
})
);
return Optional.of(result);
}
public static Optional<BigDecimal[][]> add(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
public static Optional<BigDecimal[][]> add(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
return operate(matrix1, matrix2, BigDecimal::add);
}
public static Optional<BigDecimal[][]> subtract(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
public static Optional<BigDecimal[][]> subtract(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
return operate(matrix1, matrix2, BigDecimal::subtract);
}
public static Optional<BigDecimal[][]> multiply(final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
public static Optional<BigDecimal[][]> multiply(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
if (!canMultiply(matrix1, matrix2)) {
return Optional.empty();
}
@ -71,47 +102,65 @@ public class MatrixUtil {
final BigDecimal[][] result = new BigDecimal[matrix1RowSize][matrix2ColumnSize];
IntStream.range(0, matrix1RowSize).forEach(rowIndex
-> IntStream.range(0, matrix2ColumnSize).forEach(columnIndex
-> result[rowIndex][columnIndex] = IntStream.range(0, size).mapToObj(index -> {
final BigDecimal value1 = matrix1[rowIndex][index];
final BigDecimal value2 = matrix2[index][columnIndex];
IntStream
.range(0, matrix1RowSize)
.forEach(rowIndex ->
IntStream
.range(0, matrix2ColumnSize)
.forEach(columnIndex ->
result[rowIndex][columnIndex] =
IntStream
.range(0, size)
.mapToObj(index -> {
final BigDecimal value1 =
matrix1[rowIndex][index];
final BigDecimal value2 =
matrix2[index][columnIndex];
return value1.multiply(value2);
})
.reduce(BigDecimal.ZERO, BigDecimal::add)
)
);
return value1.multiply(value2);
})
.reduce(BigDecimal.ZERO, BigDecimal::add)
)
);
return Optional.of(result);
}
public static void assertThat(final BigDecimal[][] actual, final BigDecimal[][] expected) {
public static void assertThat(
final BigDecimal[][] actual,
final BigDecimal[][] expected
) {
if (!Objects.deepEquals(actual, expected)) {
throw new AssertionError(String.format(
throw new AssertionError(
String.format(
"expected=%s but was actual=%s",
Arrays.deepToString(expected),
Arrays.deepToString(actual)
));
)
);
}
}
public static void main(final String[] args) {
{
final BigDecimal[][] matrix1 = {
{new BigDecimal(3), new BigDecimal(2)},
{new BigDecimal(0), new BigDecimal(1)},};
{ new BigDecimal(3), new BigDecimal(2) },
{ new BigDecimal(0), new BigDecimal(1) },
};
final BigDecimal[][] matrix2 = {
{new BigDecimal(1), new BigDecimal(3)},
{new BigDecimal(2), new BigDecimal(0)},};
{ new BigDecimal(1), new BigDecimal(3) },
{ new BigDecimal(2), new BigDecimal(0) },
};
final BigDecimal[][] actual = add(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
.orElseThrow(() ->
new AssertionError("Could not compute matrix!")
);
final BigDecimal[][] expected = {
{new BigDecimal(4), new BigDecimal(5)},
{new BigDecimal(2), new BigDecimal(1)}
{ new BigDecimal(4), new BigDecimal(5) },
{ new BigDecimal(2), new BigDecimal(1) },
};
assertThat(actual, expected);
@ -119,19 +168,23 @@ public class MatrixUtil {
{
final BigDecimal[][] matrix1 = {
{new BigDecimal(1), new BigDecimal(4)},
{new BigDecimal(5), new BigDecimal(6)},};
{ new BigDecimal(1), new BigDecimal(4) },
{ new BigDecimal(5), new BigDecimal(6) },
};
final BigDecimal[][] matrix2 = {
{new BigDecimal(2), new BigDecimal(0)},
{new BigDecimal(-2), new BigDecimal(-3)},};
{ new BigDecimal(2), new BigDecimal(0) },
{ new BigDecimal(-2), new BigDecimal(-3) },
};
final BigDecimal[][] actual = subtract(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
.orElseThrow(() ->
new AssertionError("Could not compute matrix!")
);
final BigDecimal[][] expected = {
{new BigDecimal(-1), new BigDecimal(4)},
{new BigDecimal(7), new BigDecimal(9)}
{ new BigDecimal(-1), new BigDecimal(4) },
{ new BigDecimal(7), new BigDecimal(9) },
};
assertThat(actual, expected);
@ -139,24 +192,26 @@ public class MatrixUtil {
{
final BigDecimal[][] matrix1 = {
{new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)},
{new BigDecimal(4), new BigDecimal(5), new BigDecimal(6)},
{new BigDecimal(7), new BigDecimal(8), new BigDecimal(9)}
{ new BigDecimal(1), new BigDecimal(2), new BigDecimal(3) },
{ new BigDecimal(4), new BigDecimal(5), new BigDecimal(6) },
{ new BigDecimal(7), new BigDecimal(8), new BigDecimal(9) },
};
final BigDecimal[][] matrix2 = {
{new BigDecimal(1), new BigDecimal(2)},
{new BigDecimal(3), new BigDecimal(4)},
{new BigDecimal(5), new BigDecimal(6)}
{ new BigDecimal(1), new BigDecimal(2) },
{ new BigDecimal(3), new BigDecimal(4) },
{ new BigDecimal(5), new BigDecimal(6) },
};
final BigDecimal[][] actual = multiply(matrix1, matrix2)
.orElseThrow(() -> new AssertionError("Could not compute matrix!"));
.orElseThrow(() ->
new AssertionError("Could not compute matrix!")
);
final BigDecimal[][] expected = {
{new BigDecimal(22), new BigDecimal(28)},
{new BigDecimal(49), new BigDecimal(64)},
{new BigDecimal(76), new BigDecimal(100)}
{ new BigDecimal(22), new BigDecimal(28) },
{ new BigDecimal(49), new BigDecimal(64) },
{ new BigDecimal(76), new BigDecimal(100) },
};
assertThat(actual, expected);

View File

@ -8,11 +8,11 @@ import java.util.Arrays;
public class Median {
public static void main(String[] args) {
assert median(new int[]{0}) == 0;
assert median(new int[]{1, 2}) == 1.5;
assert median(new int[]{4, 1, 3, 2}) == 2.5;
assert median(new int[]{1, 3, 3, 6, 7, 8, 9}) == 6;
assert median(new int[]{1, 2, 3, 4, 5, 6, 8, 9}) == 4.5;
assert median(new int[] { 0 }) == 0;
assert median(new int[] { 1, 2 }) == 1.5;
assert median(new int[] { 4, 1, 3, 2 }) == 2.5;
assert median(new int[] { 1, 3, 3, 6, 7, 8, 9 }) == 6;
assert median(new int[] { 1, 2, 3, 4, 5, 6, 8, 9 }) == 4.5;
}
/**
@ -25,7 +25,7 @@ public class Median {
Arrays.sort(values);
int length = values.length;
return length % 2 == 0
? (values[length / 2] + values[length / 2 - 1]) / 2.0
: values[length / 2];
? (values[length / 2] + values[length / 2 - 1]) / 2.0
: values[length / 2];
}
}

View File

@ -2,56 +2,56 @@ package com.thealgorithms.maths;
/*
* Java program for mobius function
* For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity.
* For any positive integer n, define μ(n) as the sum of the primitive nth roots of unity.
* It has values in {1, 0, 1} depending on the factorization of n into prime factors:
* μ(n) = +1 if n is a square-free positive integer with an even number of prime factors.
* μ(n) = 1 if n is a square-free positive integer with an odd number of prime factors.
* μ(n) = 0 if n has a squared prime factor.
* Wikipedia: https://en.wikipedia.org/wiki/M%C3%B6bius_function
*
*
* Author: Akshay Dubey (https://github.com/itsAkshayDubey)
*
*
* */
public class MobiusFunction {
/**
* This method returns μ(n) of given number n
*
* @param number Integer value which μ(n) is to be calculated
* @return 1 when number is less than or equals 1
* or number has even number of prime factors
* 0 when number has repeated prime factor
* -1 when number has odd number of prime factors
*/
static int mobius(int number) {
/**
* This method returns μ(n) of given number n
*
* @param number Integer value which μ(n) is to be calculated
* @return 1 when number is less than or equals 1
* or number has even number of prime factors
* 0 when number has repeated prime factor
* -1 when number has odd number of prime factors
*/
static int mobius(int number) {
if (number <= 0) {
//throw exception when number is less than or is zero
throw new IllegalArgumentException(
"Number must be greater than zero."
);
}
if(number <= 0) {
//throw exception when number is less than or is zero
throw new IllegalArgumentException("Number must be greater than zero.");
}
if (number == 1) {
//return 1 if number passed is less or is 1
return 1;
}
if(number == 1) {
//return 1 if number passed is less or is 1
return 1;
}
int primeFactorCount = 0;
int primeFactorCount=0;
for(int i = 1; i <= number; i++) {
//find prime factors of number
if(number % i == 0 && PrimeCheck.isPrime(i)) {
//check if number is divisible by square of prime factor
if(number % (i*i) == 0) {
//if number is divisible by square of prime factor
return 0;
}
/*increment primeFactorCount by 1
for (int i = 1; i <= number; i++) {
//find prime factors of number
if (number % i == 0 && PrimeCheck.isPrime(i)) {
//check if number is divisible by square of prime factor
if (number % (i * i) == 0) {
//if number is divisible by square of prime factor
return 0;
}
/*increment primeFactorCount by 1
if number is not divisible by square of found prime factor*/
primeFactorCount++;
}
}
return (primeFactorCount % 2 == 0) ? 1 : -1;
}
primeFactorCount++;
}
}
return (primeFactorCount % 2 == 0) ? 1 : -1;
}
}

View File

@ -14,23 +14,30 @@ import java.util.HashMap;
public class Mode {
public static void main(String[] args) {
/* Test array of integers */
assert (mode(new int[]{})) == null;
assert Arrays.equals(mode(new int[]{5}), new int[]{5});
assert Arrays.equals(mode(new int[]{1, 2, 3, 4, 5}), new int[]{1, 2, 3, 4, 5});
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 8}), new int[]{7});
assert Arrays.equals(mode(new int[]{7, 9, 9, 4, 5, 6, 7, 7, 9}), new int[]{7, 9});
assert (mode(new int[] {})) == null;
assert Arrays.equals(mode(new int[] { 5 }), new int[] { 5 });
assert Arrays.equals(
mode(new int[] { 1, 2, 3, 4, 5 }),
new int[] { 1, 2, 3, 4, 5 }
);
assert Arrays.equals(
mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 8 }),
new int[] { 7 }
);
assert Arrays.equals(
mode(new int[] { 7, 9, 9, 4, 5, 6, 7, 7, 9 }),
new int[] { 7, 9 }
);
}
/*
* Find the mode of an array of integers
*
* @param numbers array of integers
* @return mode of the array
* Find the mode of an array of integers
*
* @param numbers array of integers
* @return mode of the array
*/
public static int[] mode(int[] numbers) {
if (numbers.length == 0) {
return null;
}
@ -39,11 +46,8 @@ public class Mode {
for (int num : numbers) {
if (count.containsKey(num)) {
count.put(num, count.get(num) + 1);
} else {
count.put(num, 1);
}
}

View File

@ -5,12 +5,11 @@ import java.util.Scanner;
/*
* 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.
* actual numbers.
*/
public class NonRepeatingElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, res = 0;
System.out.println("Enter the number of elements in the array");
@ -22,7 +21,11 @@ public class NonRepeatingElement {
}
int arr[] = new int[n];
System.out.println("Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
System.out.println(
"Enter " +
n +
" elements in the array. NOTE: Only 2 elements should not repeat"
);
for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
@ -43,18 +46,17 @@ public class NonRepeatingElement {
int num1 = 0, num2 = 0;
for (i = 0; i < n; i++) {
if ((res & arr[i]) > 0)//Case 1 explained below
{
if ((res & arr[i]) > 0) { //Case 1 explained below
num1 ^= arr[i];
} else {
num2 ^= arr[i];//Case 2 explained below
num2 ^= arr[i]; //Case 2 explained below
}
}
System.out.println("The two non repeating elements are " + num1 + " and " + num2);
System.out.println(
"The two non repeating elements are " + num1 + " and " + num2
);
}
/*
Explanation of the code:
let us assume we have an array [1,2,1,2,3,4]

View File

@ -6,7 +6,17 @@ package com.thealgorithms.maths;
public class NumberOfDigits {
public static void main(String[] args) {
int[] numbers = {0, 12, 123, 1234, -12345, 123456, 1234567, 12345678, 123456789};
int[] numbers = {
0,
12,
123,
1234,
-12345,
123456,
1234567,
12345678,
123456789,
};
for (int i = 0; i < numbers.length; ++i) {
assert numberOfDigits(numbers[i]) == i + 1;
assert numberOfDigitsFast(numbers[i]) == i + 1;
@ -37,7 +47,9 @@ public class NumberOfDigits {
* @return number of digits of given number
*/
private static int numberOfDigitsFast(int number) {
return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1);
return number == 0
? 1
: (int) Math.floor(Math.log10(Math.abs(number)) + 1);
}
/**

View File

@ -3,7 +3,6 @@ package com.thealgorithms.maths;
public class PalindromeNumber {
public static void main(String[] args) {
assert isPalindrome(12321);
assert !isPalindrome(1234);
assert isPalindrome(1);

View File

@ -24,7 +24,11 @@ public class ParseInteger {
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
for (
int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length();
i < length;
++i
) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("s=" + s);
}

View File

@ -1,5 +1,7 @@
package com.thealgorithms.maths;
public class 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
@ -31,8 +33,7 @@ public class PascalTriangle {
*
*/
public static int[][] pascal(int n)
{
public static int[][] pascal(int n) {
/**
* @param arr An auxiliary array to store generated pascal triangle values
* @return
@ -42,22 +43,18 @@ public class PascalTriangle {
* @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++)
{
for (int line = 0; line < n; line++) {
/**
* @Every line has number of integers equal to line number
*/
for (int i = 0; i <= line; i++)
{
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;
// The rest elements are sum of values just above and left of above
else
arr[line][i] = arr[line-1][i-1] + arr[line-1][i];
if (line == i || i == 0) arr[line][i] = 1;
// The rest elements are sum of values just above and left of above
else arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i];
}
}
return arr;
}
}

View File

@ -1,11 +1,13 @@
package com.thealgorithms.maths;
public class Perimeter {
public static void main(String[] args) {
System.out.println(perimeter_polygon(5,4));
System.out.println(perimeter_rectangle(3,4));
System.out.printf("%,3f",circumference(5));
System.out.println(perimeter_polygon(5, 4));
System.out.println(perimeter_rectangle(3, 4));
System.out.printf("%,3f", circumference(5));
}
// Perimeter of different 2D geometrical shapes
/**
*Calculate the Perimeter of polygon.
@ -13,26 +15,28 @@ public class Perimeter {
* @parameter number of sides.
* @return Perimeter of given polygon
*/
public static float perimeter_polygon( int n, float side){
float perimeter = n*side;
public static float perimeter_polygon(int n, float side) {
float perimeter = n * side;
return perimeter;
}
/**
*Calculate the Perimeter of rectangle.
* @parameter length and breadth.
* @return Perimeter of given rectangle
*/
public static float perimeter_rectangle( float length, float breadth){
float perimeter = 2*(length + breadth);
public static float perimeter_rectangle(float length, float breadth) {
float perimeter = 2 * (length + breadth);
return perimeter;
}
/**
*Calculate the circumference of circle.
* @parameter radius of circle.
* @return circumference of given circle.
*/
public static double circumference( float r){
double circumference = 2*Math.PI*r;
public static double circumference(float r) {
double circumference = 2 * Math.PI * r;
return circumference;
}
}

View File

@ -22,18 +22,25 @@ public class PiNilakantha {
*/
public static double calculatePi(int iterations) {
if (iterations < 0 || iterations > 500) {
throw new IllegalArgumentException("Please input Integer Number between 0 and 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));
pi =
pi +
4.0 /
(divCounter * (divCounter + 1) * (divCounter + 2));
} else {
pi = pi - 4.0 / (divCounter * (divCounter + 1) * (divCounter + 2));
pi =
pi -
4.0 /
(divCounter * (divCounter + 1) * (divCounter + 2));
}
divCounter += 2;

View File

@ -35,40 +35,40 @@ package com.thealgorithms.maths;
*
* */
public class 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, y = 2, 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;
}
/**
* 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, y = 2, 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;
}
}

View File

@ -12,13 +12,17 @@ public class PrimeCheck {
if (isPrime(n)) {
System.out.println("algo1 verify that " + n + " is a prime number");
} else {
System.out.println("algo1 verify that " + n + " is not a prime number");
System.out.println(
"algo1 verify that " + n + " is not a prime number"
);
}
if (fermatPrimeChecking(n, 20)) {
System.out.println("algo2 verify that " + n + " is a prime number");
} else {
System.out.println("algo2 verify that " + n + " is not a prime number");
System.out.println(
"algo2 verify that " + n + " is not a prime number"
);
}
scanner.close();
}
@ -52,19 +56,18 @@ public class PrimeCheck {
* @param n the number
* @return {@code true} if {@code n} is prime
*/
public static boolean fermatPrimeChecking(int n, int iteration){
long a;
int up = n - 2, down = 2;
for(int i=0;i<iteration;i++){
a = (long)Math.floor(Math.random()*(up - down + 1) + down);
if(modPow(a,n-1,n) != 1){
return false;
public static boolean fermatPrimeChecking(int n, int iteration) {
long a;
int up = n - 2, down = 2;
for (int i = 0; i < iteration; i++) {
a = (long) Math.floor(Math.random() * (up - down + 1) + down);
if (modPow(a, n - 1, n) != 1) {
return false;
}
}
}
return true;
return true;
}
/**
* *
* @param a basis
@ -72,10 +75,9 @@ public class PrimeCheck {
* @param c modulo
* @return (a^b) mod c
*/
private static long modPow(long a, long b, long c){
private static long modPow(long a, long b, long c) {
long res = 1;
for (int i = 0; i < b; i++)
{
for (int i = 0; i < b; i++) {
res *= a;
res %= c;
}

View File

@ -1,39 +1,38 @@
package com.thealgorithms.maths;
/*
* Authors:
* (1) Aitor Fidalgo Sánchez (https://github.com/aitorfi)
* 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 class PrimeFactorization {
public static List<Integer> pfactors(int n) {
List<Integer> primeFactors = new ArrayList<>();
public static List<Integer> pfactors(int n) {
List<Integer> primeFactors = new ArrayList<>();
if (n == 0) {
return primeFactors;
}
if (n == 0) {
return primeFactors;
}
while (n % 2 == 0) {
primeFactors.add(2);
n /= 2;
}
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;
}
}
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;
}
if (n > 2) {
primeFactors.add(n);
}
return primeFactors;
}
}

View File

@ -5,34 +5,30 @@ package com.thealgorithms.maths;
* 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 class PronicNumber {
/**
/**
* This method checks if the given number is pronic number or non-pronic number
*
* @param input_number Integer value which is to be checked if is a pronic number or not
* @param input_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
*/
static boolean isPronic(int input_number) {
//Iterating from 0 to input_number
for(int i = 0; i <= input_number; i++) {
//Checking if product of i and (i+1) is equals input_number
if(i * (i+1) == input_number && i != input_number) {
//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;
}
static boolean isPronic(int input_number) {
//Iterating from 0 to input_number
for (int i = 0; i <= input_number; i++) {
//Checking if product of i and (i+1) is equals input_number
if (i * (i + 1) == input_number && i != input_number) {
//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;
}
}

View File

@ -1,8 +1,8 @@
package com.thealgorithms.maths;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ReverseNumber {

View File

@ -13,28 +13,70 @@ public class 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"};
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"};
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"};
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"};
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
)
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];
return (
RN_M[number / 1000] +
RN_C[number % 1000 / 100] +
RN_X[number % 100 / 10] +
RN_I[number % 10]
);
}
}

View File

@ -25,7 +25,9 @@ public class SimpsonIntegration {
// Check so that N is even
if (N % 2 != 0) {
System.out.println("N must be even number for Simpsons method. Aborted");
System.out.println(
"N must be even number for Simpsons method. Aborted"
);
System.exit(1);
}
@ -83,7 +85,6 @@ public class SimpsonIntegration {
// 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);
// return Math.sqrt(x);
}
}

View File

@ -1,15 +1,14 @@
package com.thealgorithms.maths;
public class SquareRootWithBabylonianMethod {
/**
* get the value, return the square root
*
* @param num contains elements
* @return the square root of num
*/
public static float square_Root(float num)
{
public static float square_Root(float num) {
float a = num;
float b = 1;
double e = 0.000001;
@ -19,5 +18,4 @@ public class SquareRootWithBabylonianMethod {
}
return a;
}
}

View File

@ -3,30 +3,28 @@ package com.thealgorithms.maths;
import java.util.Scanner;
/*
*To learn about the method, visit the link below :
* https://en.wikipedia.org/wiki/Newton%27s_method
*
* To obtain the square root, no built-in functions should be used
*
* The formula to calculate the root is : root = 0.5(x + n/x),
* here, n is the no. whose square root has to be calculated and
* x has to be guessed such that, the calculation should result into
* the square root of n.
* And the root will be obtained when the error < 0.5 or the precision value can also
* be changed according to the user preference.
*/
*To learn about the method, visit the link below :
* https://en.wikipedia.org/wiki/Newton%27s_method
*
* To obtain the square root, no built-in functions should be used
*
* The formula to calculate the root is : root = 0.5(x + n/x),
* here, n is the no. whose square root has to be calculated and
* x has to be guessed such that, the calculation should result into
* the square root of n.
* And the root will be obtained when the error < 0.5 or the precision value can also
* be changed according to the user preference.
*/
public class SquareRootWithNewtonRaphsonMethod {
public static double squareRoot (int n) {
public static double squareRoot(int n) {
double x = n; //initially taking a guess that x = n.
double root = 0.5 * (x + n / x); //applying Newton-Raphson Method.
double x = n; //initially taking a guess that x = n.
double root = 0.5 * (x + n/x); //applying Newton-Raphson Method.
while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here.
x = root; //decreasing the value of x to root, i.e. decreasing the guess.
root = 0.5 * (x + n/x);
while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here.
x = root; //decreasing the value of x to root, i.e. decreasing the guess.
root = 0.5 * (x + n / x);
}
return root;

View File

@ -1,22 +1,18 @@
package com.thealgorithms.maths;
public class StandardDeviation {
public static double stdDev(double[] data)
{
double var = 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++)
{
var += Math.pow((data[j] - avg), 2);
}
var /= data.length;
return Math.sqrt(var);
}
public static double stdDev(double[] data) {
double var = 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++) {
var += Math.pow((data[j] - avg), 2);
}
var /= data.length;
return Math.sqrt(var);
}
}

View File

@ -1,9 +1,9 @@
package com.thealgorithms.maths;
public class StandardScore {
public static double zScore(double num, double mean, double stdDev)
{
double z = (num - mean)/stdDev;
return z;
}
public static double zScore(double num, double mean, double stdDev) {
double z = (num - mean) / stdDev;
return z;
}
}

View File

@ -13,7 +13,6 @@ package com.thealgorithms.maths;
public class SumOfArithmeticSeries {
public static void main(String[] args) {
/* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */
assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0;
@ -37,7 +36,13 @@ public class SumOfArithmeticSeries {
* @param numOfTerms the total terms of an arithmetic series
* @return sum of given arithmetic series
*/
private static double sumOfSeries(double firstTerm, double commonDiff, int numOfTerms) {
return numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff);
private static double sumOfSeries(
double firstTerm,
double commonDiff,
int numOfTerms
) {
return (
numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff)
);
}
}

View File

@ -3,13 +3,17 @@ package com.thealgorithms.maths;
public class SumOfDigits {
public static void main(String[] args) {
assert sumOfDigits(-123) == 6 && sumOfDigitsRecursion(-123) == 6 && sumOfDigitsFast(-123) == 6;
assert sumOfDigits(-123) == 6 &&
sumOfDigitsRecursion(-123) == 6 &&
sumOfDigitsFast(-123) == 6;
assert sumOfDigits(0) == 0 && sumOfDigitsRecursion(0) == 0 && sumOfDigitsFast(0) == 0;
assert sumOfDigits(0) == 0 &&
sumOfDigitsRecursion(0) == 0 &&
sumOfDigitsFast(0) == 0;
assert sumOfDigits(12345) == 15
&& sumOfDigitsRecursion(12345) == 15
&& sumOfDigitsFast(12345) == 15;
assert sumOfDigits(12345) == 15 &&
sumOfDigitsRecursion(12345) == 15 &&
sumOfDigitsFast(12345) == 15;
}
/**
@ -38,7 +42,9 @@ public class SumOfDigits {
public static int sumOfDigitsRecursion(int number) {
number = number < 0 ? -number : number;
/* calculate abs value */
return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
return number < 10
? number
: number % 10 + sumOfDigitsRecursion(number / 10);
}
/**

View File

@ -18,7 +18,11 @@ public class TrinomialTriangle {
return 0;
}
return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1);
return (
TrinomialValue(n - 1, k - 1) +
TrinomialValue(n - 1, k) +
TrinomialValue(n - 1, k + 1)
);
}
public static void printTrinomial(int n) {

View File

@ -19,7 +19,6 @@ import java.util.Collections;
public class VampireNumber {
public static void main(String[] args) {
test(10, 1000);
}
@ -32,15 +31,30 @@ public class VampireNumber {
// System.out.println(i+ " "+ j);
if (isVampireNumber(i, j, true)) {
countofRes++;
res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i * j + ")" + "\n");
res.append(
"" +
countofRes +
": = ( " +
i +
"," +
j +
" = " +
i *
j +
")" +
"\n"
);
}
}
}
System.out.println(res);
}
static boolean isVampireNumber(int a, int b, boolean noPseudoVamireNumbers) {
static boolean isVampireNumber(
int a,
int b,
boolean noPseudoVamireNumbers
) {
// this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for
// example
// 126 = 6 x 21
@ -58,7 +72,6 @@ public class VampireNumber {
// methode to Split the numbers to Digits
static String splitIntoDigits(int num, int num2) {
StringBuilder res = new StringBuilder();
ArrayList<Integer> digits = new ArrayList<>();

View File

@ -121,7 +121,5 @@ public class VectorCrossProduct {
//Determine dot product
int dotProd = A.dotProduct(B);
System.out.println("Dot Product of A and B: " + dotProd);
}
}

View File

@ -1,11 +1,9 @@
package com.thealgorithms.maths;
/* Find volume of various shapes.*/
public class Volume {
public static void main(String[] args) {
/* test cube */
assert Double.compare(volumeCube(7), 343.0) == 0;
@ -23,13 +21,12 @@ public class Volume {
/* test cone */
assert Double.compare(volumeCone(5, 7), 916.297857297023) == 0;
/*test prism*/
assert Double.compare(volumePrism(10, 2), 20.0) == 0;
/*test pyramid*/
assert Double.compare(volumePyramid(10, 3), 10.0) == 0;
}
/**
@ -50,7 +47,11 @@ public class Volume {
* @param length of cuboid
* @return volume of given cuboid
*/
private static double volumeCuboid(double width, double height, double length) {
private static double volumeCuboid(
double width,
double height,
double length
) {
return width * height * length;
}
@ -95,7 +96,7 @@ public class Volume {
private static double volumeCone(double radius, double height) {
return Math.PI * radius * radius * height / 3;
}
/**
* Calculate the volume of a prism.
*
@ -106,7 +107,7 @@ public class Volume {
private static double volumePrism(double basearea, double height) {
return basearea * height;
}
/**
* Calculate the volume of a pyramid.
*