style: format code (#4212)

close #4204
This commit is contained in:
acbin
2023-06-09 18:52:05 +08:00
committed by GitHub
parent ad03086f54
commit 00282efd8b
521 changed files with 5233 additions and 7309 deletions

View File

@ -21,11 +21,8 @@ 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);
}
@ -64,7 +61,8 @@ public record ADTFraction(int numerator, int denominator) {
/**
* Calculates the result of the fraction.
*
* @return The numerical result of the division between {@code numerator} and {@code denominator}
* @return The numerical result of the division between {@code numerator} and {@code
* denominator}
*/
public float value() {
return (float) this.numerator / this.denominator;

View File

@ -15,12 +15,9 @@ public class AbsoluteMin {
throw new IllegalArgumentException("Numbers array cannot be empty");
}
var absMinWrapper = new Object() {
int value = numbers[0];
};
var absMinWrapper = new Object() { int value = numbers[0]; };
Arrays
.stream(numbers)
Arrays.stream(numbers)
.skip(1)
.filter(number -> Math.abs(number) < Math.abs(absMinWrapper.value))
.forEach(number -> absMinWrapper.value = number);

View File

@ -18,28 +18,24 @@ public class AliquotSum {
* @return aliquot sum of given {@code number}
*/
public static int getAliquotValue(int number) {
var sumWrapper = new Object() {
int value = 0;
};
var sumWrapper = new Object() { int value = 0; };
IntStream
.iterate(1, i -> ++i)
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;
if (n <= 0) return -1;
int sum = 1;
double root = Math.sqrt(n);
/*
@ -56,9 +52,9 @@ public class AliquotSum {
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 -= root;
// 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 -= root;
return sum;
}
}

View File

@ -21,9 +21,8 @@ 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 */
/* Res -> Int Range of 1 till 3000there are 3Amicable_numbers These are 1: = ( 220,284)
2: = ( 1184,1210) 3: = ( 2620,2924) So it worked */
}
/**
@ -32,8 +31,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
/* 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
* */
StringBuilder res = new StringBuilder();
int countofRes = 0;
@ -42,22 +42,14 @@ 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 "
);
res.insert(0,
"Int Range of " + startValue + " till " + stopValue + " there are " + countofRes
+ " Amicable_numbers.These are \n ");
System.out.println(res);
}
@ -69,12 +61,8 @@ 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)));
}
/**

View File

@ -135,7 +135,8 @@ public class Area {
* @param height height of trapezium
* @return area of given trapezium
*/
public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) {
public static double surfaceAreaTrapezium(
final double base1, final double base2, final double height) {
if (base1 <= 0) {
throw new IllegalArgumentException(POSITIVE_BASE + 1);
}

View File

@ -20,15 +20,15 @@ public class AutomorphicNumber {
* {@code false}
*/
public static boolean isAutomorphic(long n) {
if (n < 0)
return false;
if (n < 0) return false;
long square = n * n; // Calculating square of the number
long t = n, 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
long lastDigits
= square % (long) Math.pow(10, numberOfdigits); // Extracting last Digits of square
return n == lastDigits;
}
@ -40,8 +40,7 @@ public class AutomorphicNumber {
* {@code false}
*/
public static boolean isAutomorphic2(long n) {
if (n < 0)
return false;
if (n < 0) return false;
long square = n * n; // Calculating square of the number
return String.valueOf(square).endsWith(String.valueOf(n));
}
@ -55,8 +54,7 @@ public class AutomorphicNumber {
*/
public static boolean isAutomorphic3(String s) {
BigInteger n = new BigInteger(s);
if (n.signum() == -1)
return false; //if number is negative, return false
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));
}

View File

@ -17,13 +17,11 @@ public class BinomialCoefficient {
*
* @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
* @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;
@ -35,9 +33,7 @@ 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,14 +39,14 @@ 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);
/* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT to have the same length with the signal and not bigger */
/* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT
* to have the same length with the signal and not bigger */
FFTBluestein.fftBluestein(a, false);
FFTBluestein.fftBluestein(b, false);
ArrayList<FFT.Complex> convolved = new ArrayList<>();

View File

@ -27,8 +27,9 @@ public class Convolution {
C[i] = Σ (A[k]*B[i-k])
k=0
It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <= B.length - 1
From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get the conditions below.
It's obvious that: 0 <= k <= A.length , 0 <= i <= A.length + B.length - 2 and 0 <= i-k <=
B.length - 1 From the last inequality we get that: i - B.length + 1 <= k <= i and thus we get
the conditions below.
*/
for (int i = 0; i < convolved.length; i++) {
convolved[i] = 0;

View File

@ -43,14 +43,13 @@ 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);
/* 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) */
/* 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<>();
@ -59,7 +58,9 @@ 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

@ -37,10 +37,10 @@ public class DeterminantOfMatrix {
return det;
}
//Driver Method
// Driver Method
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//Input Matrix
// Input Matrix
System.out.println("Enter matrix size (Square matrix only)");
int n = in.nextInt();
System.out.println("Enter matrix");

View File

@ -1,7 +1,9 @@
/** Author : Suraj Kumar Modi
/**
* Author : Suraj Kumar Modi
* https://github.com/skmodi649
*/
/** You are given a number n. You need to find the digital root of n.
/**
* 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:
@ -19,7 +21,8 @@
* sum of digit of 45 is 9 which is a single
* digit number.
*/
/** Algorithm :
/**
* 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
@ -32,14 +35,16 @@
* 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
* Step 5 : In main method simply take n as input and then call digitalRoot(int n) function and
* print the result
*/
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));
@ -55,7 +60,6 @@ class DigitalRoot {
}
} // 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 :

View File

@ -2,23 +2,13 @@ package com.thealgorithms.maths;
public class DistanceFormula {
public static double euclideanDistance(
double x1,
double y1,
double x2,
double y2
) {
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
) {
public static double manhattanDistance(double x1, double y1, double x2, double y2) {
return Math.abs(x1 - x2) + Math.abs(y1 - y2);
}

View File

@ -10,7 +10,7 @@ import java.io.*;
public class DudeneyNumber {
//returns True if the number is a Dudeney number and False if it is not a Dudeney number.
// returns True if the number is a Dudeney number and False if it is not a Dudeney number.
public static boolean isDudeney(int n) {
// Calculating Cube Root
int cube_root = (int) (Math.round((Math.pow(n, 1.0 / 3.0))));
@ -19,7 +19,7 @@ public class DudeneyNumber {
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 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
@ -32,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.
return cube_root == sum_of_digits;
}
}

View File

@ -37,15 +37,8 @@ public class EulerMethod {
// 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.printf("x: %1$f; y: %2$f%n", point[0], point[1]));
}
@ -60,16 +53,10 @@ public class EulerMethod {
* @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
) {
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"
);
throw new IllegalArgumentException("stepSize should be greater than zero");
}
return yCurrent + stepSize * differentialEquation.apply(xCurrent, yCurrent);
}
@ -86,36 +73,26 @@ public class EulerMethod {
* @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
) {
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"
);
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

@ -180,10 +180,7 @@ 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();
@ -220,11 +217,7 @@ 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);
@ -236,11 +229,7 @@ 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

@ -30,7 +30,8 @@ public class FFTBluestein {
ArrayList<FFT.Complex> an = new ArrayList<>();
ArrayList<FFT.Complex> bn = new ArrayList<>();
/* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols used)*/
/* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols
* used)*/
for (int i = 0; i < bnSize; i++) {
bn.add(new FFT.Complex());
}
@ -38,26 +39,16 @@ 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,7 +21,8 @@ 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

@ -1,4 +1,5 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
@ -22,7 +23,8 @@ public class 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
* 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) {
@ -39,17 +41,16 @@ public class FastInverseSqrt {
}
/**
* 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
* 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)
* 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,31 +25,24 @@ public class FibonacciJavaStreams {
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
);
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));
return results.isEmpty() ? 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)
);
String.format("expected=%s but was actual=%s", expected, actual));
}
}
@ -91,39 +84,28 @@ 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

@ -17,10 +17,8 @@ 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();
}
/**
@ -52,8 +50,6 @@ 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,10 +20,8 @@ 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();
}
/**
@ -55,8 +53,6 @@ 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

@ -1,10 +1,10 @@
/** Author : Siddhant Swarup Mallick
/**
* Author : Siddhant Swarup Mallick
* Github : https://github.com/siddhant2002
*/
/** Program description - To find the FrizzyNumber*/
package com.thealgorithms.maths;
public class FrizzyNumber {
@ -16,7 +16,7 @@ public class FrizzyNumber {
* 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
@ -24,8 +24,7 @@ public class FrizzyNumber {
public static double getNthFrizzy(int base, int n) {
double final1 = 0.0;
int i = 0;
do
{
do {
final1 += Math.pow(base, i++) * (n % 2);
} while ((n /= 2) > 0);
return final1;

View File

@ -48,14 +48,10 @@ 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

@ -4,10 +4,7 @@ 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;
@ -27,11 +24,7 @@ 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++) {
@ -46,11 +39,7 @@ 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;

View File

@ -1,7 +1,8 @@
package com.thealgorithms.maths;
/*
* Algorithm explanation: https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015.
* Algorithm explanation:
* https://technotip.com/6774/c-program-to-find-generic-root-of-a-number/#:~:text=Generic%20Root%3A%20of%20a%20number,get%20a%20single%2Ddigit%20output.&text=For%20Example%3A%20If%20user%20input,%2B%204%20%2B%205%20%3D%2015.
*/
public class GenericRoot {

View File

@ -12,8 +12,7 @@ public class HarshadNumber {
* {@code false}
*/
public static boolean isHarshad(long n) {
if (n <= 0)
return false;
if (n <= 0) return false;
long t = n;
int sumOfDigits = 0;
@ -34,8 +33,7 @@ public class HarshadNumber {
*/
public static boolean isHarshad(String s) {
long n = Long.valueOf(s);
if (n <= 0)
return false;
if (n <= 0) return false;
int sumOfDigits = 0;
for (char ch : s.toCharArray()) {

View File

@ -1,15 +1,21 @@
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.
/**
* 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:
/**
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.
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
*/

View File

@ -35,10 +35,7 @@ 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

@ -6,12 +6,12 @@ import java.util.*;
public class KaprekarNumbers {
/* 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. */
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 List<Long> kaprekarNumberInRange(long start, long end)
throws Exception {
public static List<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<>();
@ -34,32 +34,13 @@ public class KaprekarNumbers {
BigInteger leftDigits1 = BigInteger.ZERO;
BigInteger leftDigits2;
if (numberSquared.toString().contains("0")) {
leftDigits1 =
new BigInteger(
numberSquared
.toString()
.substring(0, numberSquared.toString().indexOf("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()
)
);
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,43 @@ 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

@ -1,52 +1,48 @@
package com.thealgorithms.maths;
/* This is a program to check if a number is a Krishnamurthy number or not.
A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal to the number itself.
For example, 1, 2 and 145 are Krishnamurthy numbers.
Krishnamurthy number is also referred to as a Strong number.
A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal
to the number itself. For example, 1, 2 and 145 are Krishnamurthy numbers. 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.
// returns True if the number is a Krishnamurthy number and False if it is not.
public static boolean isKMurthy(int n) {
//initialising the variable s that will store the sum of the factorials of the digits to 0
// initialising the variable s that will store the sum of the factorials of the digits to 0
int s = 0;
//storing the number n in a temporary variable tmp
// storing the number n in a temporary variable tmp
int tmp = n;
//Krishnamurthy numbers are positive
// Krishnamurthy numbers are positive
if (n <= 0) {
return false;
} //checking if the number is a Krishnamurthy number
} // checking if the number is a Krishnamurthy number
else {
while (n != 0) {
//initialising the variable fact that will store the factorials of the digits
// initialising the variable fact that will store the factorials of the digits
int fact = 1;
//computing factorial of each digit
// computing factorial of each digit
for (int i = 1; i <= n % 10; i++) {
fact = fact * i;
}
//computing the sum of the factorials
// computing the sum of the factorials
s = s + fact;
//discarding the digit for which factorial has been calculated
// discarding the digit for which factorial has been calculated
n = n / 10;
}
//evaluating if sum of the factorials of the digits equals the number itself
// evaluating if sum of the factorials of the digits equals the number itself
return tmp == s;
}
}
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

@ -20,9 +20,7 @@ public class LeastCommonMultiple {
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));
}
/*

View File

@ -1,8 +1,8 @@
package com.thealgorithms.maths;
/**
* https://en.wikipedia.org/wiki/Leonardo_number
*/
/**
* https://en.wikipedia.org/wiki/Leonardo_number
*/
public class LeonardoNumber {
/**

View File

@ -28,38 +28,26 @@ public final class LinearDiophantineEquationsSolver {
}
private static GcdSolutionWrapper gcd(
final int a,
final int b,
final GcdSolutionWrapper previous
) {
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;
@ -103,11 +91,14 @@ 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 {
@ -128,10 +119,7 @@ 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() {
@ -157,15 +145,9 @@ public final class LinearDiophantineEquationsSolver {
@Override
public String toString() {
return (
"GcdSolutionWrapper[" +
"gcd=" +
gcd +
", " +
"solution=" +
solution +
']'
);
return ("GcdSolutionWrapper["
+ "gcd=" + gcd + ", "
+ "solution=" + solution + ']');
}
}
}

View File

@ -24,13 +24,11 @@ public class LiouvilleLambdaFunction {
*/
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."
);
// 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 1 if size of prime factor list is even, -1 otherwise
return PrimeFactorization.pfactors(number).size() % 2 == 0 ? 1 : -1;
}
}

View File

@ -1,17 +1,19 @@
// Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
// Given two integers dividend and divisor, divide two integers without using multiplication,
// division, and mod operator.
//
// The integer division should truncate toward zero, which means losing its fractional part. For example, 8.345 would be truncated to 8,
// and -2.7335 would be truncated to -2.
// My method used Long Division, here is the source "https://en.wikipedia.org/wiki/Long_division"
// The integer division should truncate toward zero, which means losing its fractional part.
// For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. My
// method used Long Division, here is the source
// "https://en.wikipedia.org/wiki/Long_division"
package com.thealgorithms.maths;
public class LongDivision {
public static int divide(int dividend, int divisor) {
public static int divide(int dividend, int divisor) {
long new_dividend_1 = dividend;
long new_divisor_1 = divisor;
if(divisor == 0){
if (divisor == 0) {
return 0;
}
if (dividend < 0) {
@ -32,7 +34,6 @@ public static int divide(int dividend, int divisor) {
String remainder = "";
for (int i = 0; i < dividend_string.length(); i++) {
String part_v1 = remainder + "" + dividend_string.substring(last_index, i + 1);
long part_1 = Long.parseLong(part_v1);
@ -57,7 +58,7 @@ public static int divide(int dividend, int divisor) {
}
if (!(part_1 == 0)) {
remainder = String.valueOf(part_1);
}else{
} else {
remainder = "";
}
@ -76,6 +77,5 @@ public static int divide(int dividend, int divisor) {
} catch (NumberFormatException e) {
return 2147483647;
}
}
}

View File

@ -13,9 +13,7 @@ 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

@ -2,8 +2,9 @@ package com.thealgorithms.maths;
import java.util.*;
/*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.*/
/*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 class MagicSquare {
public static void main(String[] args) {
@ -22,10 +23,7 @@ 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 {

View File

@ -18,33 +18,18 @@ public class MatrixUtil {
}
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
);
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,
public static Optional<BigDecimal[][]> operate(final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2,
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation
) {
final BiFunction<BigDecimal, BigDecimal, BigDecimal> operation) {
if (!hasEqualSizes(matrix1, matrix2)) {
return Optional.empty();
}
@ -54,43 +39,29 @@ 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
) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return operate(matrix1, matrix2, BigDecimal::add);
}
public static Optional<BigDecimal[][]> subtract(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
return operate(matrix1, matrix2, BigDecimal::subtract);
}
public static Optional<BigDecimal[][]> multiply(
final BigDecimal[][] matrix1,
final BigDecimal[][] matrix2
) {
final BigDecimal[][] matrix1, final BigDecimal[][] matrix2) {
if (!canMultiply(matrix1, matrix2)) {
return Optional.empty();
}
@ -102,65 +73,49 @@ 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(
"expected=%s but was actual=%s",
Arrays.deepToString(expected),
Arrays.deepToString(actual)
)
);
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!")
);
final BigDecimal[][] actual
= add(matrix1, matrix2)
.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);
@ -168,23 +123,22 @@ 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!")
);
final BigDecimal[][] actual
= subtract(matrix1, matrix2)
.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);
@ -192,26 +146,25 @@ 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!")
);
final BigDecimal[][] actual
= multiply(matrix1, matrix2)
.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

@ -15,8 +15,7 @@ public class Median {
public static double median(int[] values) {
Arrays.sort(values);
int length = values.length;
return length % 2 == 0
? (values[length / 2] + values[length / 2 - 1]) / 2.0
: values[length / 2];
return length % 2 == 0 ? (values[length / 2] + values[length / 2 - 1]) / 2.0
: values[length / 2];
}
}

View File

@ -25,29 +25,27 @@ public class MobiusFunction {
*/
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."
);
// 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 passed is less or is 1
return 1;
}
int primeFactorCount = 0;
for (int i = 1; i <= number; i++) {
//find prime factors of number
// find prime factors of number
if (number % i == 0 && PrimeCheck.isPrime(i)) {
//check if number is divisible by square of prime factor
// check if number is divisible by square of prime factor
if (number % (i * i) == 0) {
//if number is divisible by square of prime factor
// 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*/
/*increment primeFactorCount by 1
if number is not divisible by square of found prime factor*/
primeFactorCount++;
}
}

View File

@ -16,19 +16,10 @@ 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 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});
}
/*

View File

@ -4,8 +4,8 @@ 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.
* Reason to use bitwise operator: It makes our program faster as we are operating on bits and not
* on actual numbers.
*/
public class NonRepeatingElement {
@ -15,17 +15,14 @@ public class NonRepeatingElement {
System.out.println("Enter the number of elements in the array");
int n = sc.nextInt();
if ((n & 1) == 1) {
//Not allowing odd number of elements as we are expecting 2 non repeating numbers
// Not allowing odd number of elements as we are expecting 2 non repeating numbers
System.out.println("Array should contain even number of elements");
return;
}
int[] arr = new int[n];
System.out.println(
"Enter " +
n +
" elements in the array. NOTE: Only 2 elements should not repeat"
);
"Enter " + n + " elements in the array. NOTE: Only 2 elements should not repeat");
for (i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
@ -36,40 +33,38 @@ public class NonRepeatingElement {
System.out.println("Unable to close scanner" + e);
}
//Find XOR of the 2 non repeating elements
// Find XOR of the 2 non repeating elements
for (i = 0; i < n; i++) {
res ^= arr[i];
}
//Finding the rightmost set bit
// Finding the rightmost set bit
res = res & (-res);
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]
Property of XOR: num ^ num = 0.
If we XOR all the elemnets 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 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 Bitise AND this res with all the elements in our array
Property of XOR: num ^ num = 0.
If we XOR all the elemnets 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 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 Bitise AND this res with all the elements in our
array
1. Result will come non zero number
2. 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.
This is how we will get non repeating elements with the help of bitwise operators.
*/
}

View File

@ -1,10 +1,9 @@
package com.thealgorithms.maths;
import java.util.HashMap;
import java.lang.IllegalArgumentException;
import java.util.ArrayList;
import java.util.Arrays;
import java.lang.IllegalArgumentException;
import java.util.HashMap;
/**
* @brief class computing the n-th ugly number (when they are sorted)

View File

@ -47,9 +47,7 @@ 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

@ -24,11 +24,7 @@ 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

@ -3,18 +3,19 @@ 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
* the French mathematician Blaise Pascal, although other mathematicians studied it centuries before
* him in India, Persia, China, Germany, and Italy.
*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. *
* 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
@ -51,7 +52,8 @@ public class PascalTriangle {
// 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];
else
arr[line][i] = arr[line - 1][i - 1] + arr[line - 1][i];
}
}

View File

@ -17,7 +17,7 @@ public class PerfectCube {
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
*

View File

@ -17,8 +17,7 @@ public class PerfectNumber {
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber(int number) {
if (number <= 0)
return false;
if (number <= 0) return false;
int sum = 0;
/* sum of its positive divisors */
for (int i = 1; i < number; ++i) {
@ -28,7 +27,7 @@ public class PerfectNumber {
}
return sum == number;
}
/**
* Check if {@code n} is perfect number or not
*
@ -36,11 +35,10 @@ public class PerfectNumber {
* @return {@code true} if {@code number} is perfect number, otherwise false
*/
public static boolean isPerfectNumber2(int n) {
if (n <= 0)
return false;
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.
@ -55,10 +53,10 @@ public class PerfectNumber {
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 -= root;
// 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 -= root;
return sum == n;
}

View File

@ -5,8 +5,9 @@ public class Perimeter {
/**
* Calculate the Perimeter of regular polygon (equals sides)
* Examples of regular polygon are Equilateral Triangle, Square, Regular Pentagon, Regular Hexagon.
*
* 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
@ -17,15 +18,17 @@ public class Perimeter {
/**
* Calculate the Perimeter of irregular polygon (unequals sides)
* Examples of irregular polygon are scalent triangle, irregular quadrilateral, irregular Pentagon, irregular Hexagon.
*
* 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 trapezoid.
*/
public static float perimeterIrregularPolygon(float side1, float side2, float side3, float... sides) {
public static float perimeterIrregularPolygon(
float side1, float side2, float side3, float... sides) {
float perimeter = side1 + side2 + side3;
for (float side : sides) {
perimeter += side;
@ -35,7 +38,7 @@ public class Perimeter {
/**
* Calculate the Perimeter of rectangle
*
*
* @param length for length of rectangle
* @param breadth for breadth of rectangle
* @return Perimeter of given rectangle
@ -46,7 +49,7 @@ public class Perimeter {
/**
* Calculate the Perimeter or Circumference of circle.
*
*
* @param r for radius of circle.
* @return circumference of given circle.
*/

View File

@ -22,9 +22,7 @@ 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;
@ -32,15 +30,9 @@ public class PiNilakantha {
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

@ -3,12 +3,12 @@ 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.
* 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 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.
* 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
@ -20,19 +20,20 @@ package com.thealgorithms.maths;
* y ← g(g(y))
* d ← gcd(|x - y|, n)
* if d = n:
* if d = n:
* return failure
* else:
* return d
* Here x and y corresponds to xi and xj in the previous section.
* 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)
*
* 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 class PollardRho {
@ -40,7 +41,8 @@ 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
* @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) {
@ -57,13 +59,13 @@ public class PollardRho {
static int pollardRho(int number) {
int x = 2, y = 2, d = 1;
while (d == 1) {
//tortoise move
// tortoise move
x = g(x, number);
//hare move
// hare move
y = g(g(y, number), number);
//check GCD of |x-y| and number
// check GCD of |x-y| and number
d = GCD.gcd(Math.abs(x - y), number);
}
if (d == number) {

View File

@ -12,17 +12,13 @@ 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();
}

View File

@ -19,16 +19,17 @@ public class PronicNumber {
* @return true if input number is a pronic number, false otherwise
*/
static boolean isPronic(int input_number) {
//Iterating from 0 to 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
// 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 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 if product of i and (i+1) for all values from 0 to input_number is not
// equals input_number
return false;
}
}

View File

@ -12,7 +12,7 @@ public class RomanNumeralUtil {
private static final int MIN_VALUE = 1;
private static final int MAX_VALUE = 5999;
//1000-5999
// 1000-5999
private static final String[] RN_M = {
"",
"M",
@ -21,7 +21,7 @@ public class RomanNumeralUtil {
"MMMM",
"MMMMM",
};
//100-900
// 100-900
private static final String[] RN_C = {
"",
"C",
@ -34,7 +34,7 @@ public class RomanNumeralUtil {
"DCCC",
"CM",
};
//10-90
// 10-90
private static final String[] RN_X = {
"",
"X",
@ -47,7 +47,7 @@ public class RomanNumeralUtil {
"LXXX",
"XC",
};
//1-9
// 1-9
private static final String[] RN_I = {
"",
"I",
@ -64,19 +64,10 @@ public class RomanNumeralUtil {
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

@ -7,9 +7,9 @@ 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.
* 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)}
@ -25,9 +25,7 @@ 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);
}

View File

@ -1,7 +1,7 @@
package com.thealgorithms.maths;
/*
* Java program for Square free integer
* This class has a function which checks
* 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
@ -23,20 +23,21 @@ public class SquareFreeInteger {
* 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();
}
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();
}
}

View File

@ -19,11 +19,13 @@ import java.util.Scanner;
public class SquareRootWithNewtonRaphsonMethod {
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.
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);
}

View File

@ -36,13 +36,7 @@ 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,17 +3,13 @@ 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;
}
/**
@ -42,9 +38,7 @@ 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

@ -3,18 +3,18 @@ package com.thealgorithms.maths;
public class SumWithoutArithmeticOperators {
/**
* Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /).
* All the integers associated are unsigned 32-bit integers
*https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator
*@param a - It is the first number
*@param b - It is the second number
*@return returns an integer which is the sum of the first and second number
*/
* Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /).
* All the integers associated are unsigned 32-bit integers
*https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator
*@param a - It is the first number
*@param b - It is the second number
*@return returns an integer which is the sum of the first and second number
*/
public int getSum(int a, int b){
if(b==0) return a;
int sum = a^b;
int carry = (a&b)<<1;
public int getSum(int a, int b) {
if (b == 0) return a;
int sum = a ^ b;
int carry = (a & b) << 1;
return getSum(sum, carry);
}
}

View File

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

View File

@ -1,32 +1,31 @@
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)
* 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)
*
*
* */
public class TwinPrime {
/**
/**
* This method returns twin prime of the integer value passed as argument
*
* @param input_number 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;
}
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;
}
}

View File

@ -31,33 +31,17 @@ 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
) {
// this is for pseudoVampireNumbers pseudovampire number need not be of length n/2 digits for
// example
// 126 = 6 x 21
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
if (noPseudoVamireNumbers) {
if (a * 10 <= b || b * 10 <= a) {
return false;

View File

@ -45,7 +45,7 @@ public class VectorCrossProduct {
int y;
int z;
//Default constructor, initialises all three Direction Ratios to 0
// Default constructor, initialises all three Direction Ratios to 0
VectorCrossProduct() {
x = 0;
y = 0;
@ -110,15 +110,15 @@ public class VectorCrossProduct {
}
static void test() {
//Create two vectors
// Create two vectors
VectorCrossProduct A = new VectorCrossProduct(1, -2, 3);
VectorCrossProduct B = new VectorCrossProduct(2, 0, 3);
//Determine cross product
// Determine cross product
VectorCrossProduct crossProd = A.crossProduct(B);
crossProd.displayVector();
//Determine dot product
// Determine dot product
int dotProd = A.dotProduct(B);
System.out.println("Dot Product of A and B: " + dotProd);
}