mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-08-02 06:03:41 +08:00
Formatted with Google Java Formatter
This commit is contained in:
@ -4,32 +4,31 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* description:
|
||||
* <p>
|
||||
* absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
|
||||
* </p>
|
||||
*
|
||||
* <p>absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
|
||||
*/
|
||||
public class AbsoluteMax {
|
||||
public static void main(String[] args) {
|
||||
int[] testnums = {-2, 0, 16};
|
||||
assert absMax(testnums) == 16;
|
||||
|
||||
int[] numbers = {3, -10, -2};
|
||||
System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
int[] testnums = {-2, 0, 16};
|
||||
assert absMax(testnums) == 16;
|
||||
|
||||
/**
|
||||
* get the value, return the absolute max value
|
||||
*
|
||||
* @param numbers contains elements
|
||||
* @return the absolute max value
|
||||
*/
|
||||
public static int absMax(int[] numbers) {
|
||||
int absMaxValue = numbers[0];
|
||||
for (int i = 1, length = numbers.length; i < length; ++i) {
|
||||
if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
|
||||
absMaxValue = numbers[i];
|
||||
}
|
||||
}
|
||||
return absMaxValue;
|
||||
int[] numbers = {3, -10, -2};
|
||||
System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
|
||||
}
|
||||
|
||||
/**
|
||||
* get the value, return the absolute max value
|
||||
*
|
||||
* @param numbers contains elements
|
||||
* @return the absolute max value
|
||||
*/
|
||||
public static int absMax(int[] numbers) {
|
||||
int absMaxValue = numbers[0];
|
||||
for (int i = 1, length = numbers.length; i < length; ++i) {
|
||||
if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
|
||||
absMaxValue = numbers[i];
|
||||
}
|
||||
}
|
||||
return absMaxValue;
|
||||
}
|
||||
}
|
||||
|
@ -4,32 +4,31 @@ import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* description:
|
||||
* <p>
|
||||
* absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
|
||||
* </p>
|
||||
*
|
||||
* <p>absMin([0, 5, 1, 11]) = 0, absMin([3 , -10, -2]) = -2
|
||||
*/
|
||||
public class AbsoluteMin {
|
||||
public static void main(String[] args) {
|
||||
int[] testnums = {4, 0, 16};
|
||||
assert absMin(testnums) == 0;
|
||||
|
||||
int[] numbers = {3, -10, -2};
|
||||
System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
int[] testnums = {4, 0, 16};
|
||||
assert absMin(testnums) == 0;
|
||||
|
||||
/**
|
||||
* get the value, returns the absolute min value min
|
||||
*
|
||||
* @param numbers contains elements
|
||||
* @return the absolute min value
|
||||
*/
|
||||
public static int absMin(int[] numbers) {
|
||||
int absMinValue = numbers[0];
|
||||
for (int i = 1, length = numbers.length; i < length; ++i) {
|
||||
if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
|
||||
absMinValue = numbers[i];
|
||||
}
|
||||
}
|
||||
return absMinValue;
|
||||
int[] numbers = {3, -10, -2};
|
||||
System.out.println("absMin(" + Arrays.toString(numbers) + ") = " + absMin(numbers));
|
||||
}
|
||||
|
||||
/**
|
||||
* get the value, returns the absolute min value min
|
||||
*
|
||||
* @param numbers contains elements
|
||||
* @return the absolute min value
|
||||
*/
|
||||
public static int absMin(int[] numbers) {
|
||||
int absMinValue = numbers[0];
|
||||
for (int i = 1, length = numbers.length; i < length; ++i) {
|
||||
if (Math.abs(numbers[i]) < Math.abs(absMinValue)) {
|
||||
absMinValue = numbers[i];
|
||||
}
|
||||
}
|
||||
return absMinValue;
|
||||
}
|
||||
}
|
||||
|
@ -4,24 +4,23 @@ import java.util.Random;
|
||||
|
||||
public class AbsoluteValue {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
|
||||
/* test 1000 random numbers */
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
int randomNumber = random.nextInt();
|
||||
assert absVal(randomNumber) == Math.abs(randomNumber);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If value is less than zero, make value positive.
|
||||
*
|
||||
* @param value a number
|
||||
* @return the absolute value of a number
|
||||
*/
|
||||
public static int absVal(int value) {
|
||||
return value < 0 ? -value : value;
|
||||
/* test 1000 random numbers */
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
int randomNumber = random.nextInt();
|
||||
assert absVal(randomNumber) == Math.abs(randomNumber);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If value is less than zero, make value positive.
|
||||
*
|
||||
* @param value a number
|
||||
* @return the absolute value of a number
|
||||
*/
|
||||
public static int absVal(int value) {
|
||||
return value < 0 ? -value : value;
|
||||
}
|
||||
}
|
||||
|
@ -1,35 +1,32 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors of n,
|
||||
* that is, all divisors of n other than n itself.
|
||||
* For example, the proper divisors of 15 (that is, the positive divisors of 15 that are not equal to 15)
|
||||
* are 1, 3 and 5, so the aliquot sum of 15 is 9 i.e. (1 + 3 + 5).
|
||||
* </p>
|
||||
* Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
|
||||
* In number theory, the aliquot sum s(n) of a positive integer n is the sum of all proper divisors
|
||||
* of n, that is, all divisors of n other than n itself. For example, the proper divisors of 15
|
||||
* (that is, the positive divisors of 15 that are not equal to 15) are 1, 3 and 5, so the aliquot
|
||||
* sum of 15 is 9 i.e. (1 + 3 + 5). Wikipedia: https://en.wikipedia.org/wiki/Aliquot_sum
|
||||
*/
|
||||
public class AliquotSum {
|
||||
public static void main(String[] args) {
|
||||
assert aliquotSum(1) == 0;
|
||||
assert aliquotSum(6) == 6;
|
||||
assert aliquotSum(15) == 9;
|
||||
assert aliquotSum(19) == 1;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert aliquotSum(1) == 0;
|
||||
assert aliquotSum(6) == 6;
|
||||
assert aliquotSum(15) == 9;
|
||||
assert aliquotSum(19) == 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the aliquot sum of an integer number
|
||||
*
|
||||
* @param number a positive integer
|
||||
* @return aliquot sum of given {@code number}
|
||||
*/
|
||||
public static int aliquotSum(int number) {
|
||||
int sum = 0;
|
||||
for (int i = 1, limit = number / 2; i <= limit; ++i) {
|
||||
if (number % i == 0) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
/**
|
||||
* Finds the aliquot sum of an integer number
|
||||
*
|
||||
* @param number a positive integer
|
||||
* @return aliquot sum of given {@code number}
|
||||
*/
|
||||
public static int aliquotSum(int number) {
|
||||
int sum = 0;
|
||||
for (int i = 1, limit = number / 2; i <= limit; ++i) {
|
||||
if (number % i == 0) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
@ -1,87 +1,87 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* Amicable numbers are two different numbers so related
|
||||
* that the sum of the proper divisors of each is equal to the other number.
|
||||
* (A proper divisor of a number is a positive factor of that number other than the number itself.
|
||||
* For example, the proper divisors of 6 are 1, 2, and 3.)
|
||||
* A pair of amicable numbers constitutes an aliquot sequence of period 2.
|
||||
* It is unknown if there are infinitely many pairs of amicable numbers.
|
||||
* *
|
||||
* <p>
|
||||
* * link: https://en.wikipedia.org/wiki/Amicable_numbers
|
||||
* * </p>
|
||||
* <p>
|
||||
* Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284
|
||||
* 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it 220
|
||||
* Amicable numbers are two different numbers so related that the sum of the proper divisors of each
|
||||
* is equal to the other number. (A proper divisor of a number is a positive factor of that number
|
||||
* other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) A pair of
|
||||
* amicable numbers constitutes an aliquot sequence of period 2. It is unknown if there are
|
||||
* infinitely many pairs of amicable numbers. *
|
||||
*
|
||||
* <p>* link: https://en.wikipedia.org/wiki/Amicable_numbers *
|
||||
*
|
||||
* <p>Simple Example : (220,284) 220 is divisible by {1,2,4,5,10,11,20,22,44,55,110 } <- Sum = 284
|
||||
* 284 is divisible by -> 1,2,4,71,142 and the Sum of that is. Yes right you probably expected it
|
||||
* 220
|
||||
*/
|
||||
|
||||
public class AmicableNumber {
|
||||
|
||||
public static void main(String[] args) {
|
||||
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 */
|
||||
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 */
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param startValue
|
||||
* @param stopValue
|
||||
* @return
|
||||
*/
|
||||
static void findAllInRange(int startValue, int stopValue) {
|
||||
/**
|
||||
* @param startValue
|
||||
* @param stopValue
|
||||
* @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
|
||||
* */
|
||||
StringBuilder res = new StringBuilder();
|
||||
int countofRes = 0;
|
||||
/* 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;
|
||||
|
||||
for (int i = startValue; i < stopValue; i++) {
|
||||
for (int j = i + 1; j <= stopValue; j++) {
|
||||
if (isAmicableNumber(i, j)) {
|
||||
countofRes++;
|
||||
res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
|
||||
}
|
||||
}
|
||||
for (int i = startValue; i < stopValue; i++) {
|
||||
for (int j = i + 1; j <= stopValue; j++) {
|
||||
if (isAmicableNumber(i, j)) {
|
||||
countofRes++;
|
||||
res.append("" + countofRes + ": = ( " + i + "," + j + ")" + "\t");
|
||||
}
|
||||
res.insert(0, "Int Range of " + startValue + " till " + stopValue + " there are " + countofRes + " Amicable_numbers.These are \n ");
|
||||
System.out.println(res.toString());
|
||||
}
|
||||
}
|
||||
res.insert(
|
||||
0,
|
||||
"Int Range of "
|
||||
+ startValue
|
||||
+ " till "
|
||||
+ stopValue
|
||||
+ " there are "
|
||||
+ countofRes
|
||||
+ " Amicable_numbers.These are \n ");
|
||||
System.out.println(res.toString());
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code numberOne and numberTwo } are AmicableNumbers or not
|
||||
*
|
||||
* @param numberOne numberTwo
|
||||
* @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers otherwise false
|
||||
*/
|
||||
static boolean isAmicableNumber(int numberOne, int numberTwo) {
|
||||
/**
|
||||
* Check if {@code numberOne and numberTwo } are AmicableNumbers or not
|
||||
*
|
||||
* @param numberOne numberTwo
|
||||
* @return {@code true} if {@code numberOne numberTwo} isAmicableNumbers 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)));
|
||||
}
|
||||
|
||||
/**
|
||||
* calculated in recursive calls the Sum of all the Dividers beside it self
|
||||
*
|
||||
* @param number div = the next to test dividely by using the modulo operator
|
||||
* @return sum of all the dividers
|
||||
*/
|
||||
static int recursiveCalcOfDividerSum(int number, int div) {
|
||||
|
||||
if (div == 1) {
|
||||
return 0;
|
||||
} else if (number % --div == 0) {
|
||||
return recursiveCalcOfDividerSum(number, div) + div;
|
||||
} else {
|
||||
return recursiveCalcOfDividerSum(number, div);
|
||||
}
|
||||
|
||||
/**
|
||||
* calculated in recursive calls the Sum of all the Dividers beside it self
|
||||
*
|
||||
* @param number div = the next to test dividely by using the modulo operator
|
||||
* @return sum of all the dividers
|
||||
*/
|
||||
static int recursiveCalcOfDividerSum(int number, int div) {
|
||||
|
||||
if (div == 1) {
|
||||
return 0;
|
||||
} else if (number % --div == 0) {
|
||||
return recursiveCalcOfDividerSum(number, div) + div;
|
||||
} else {
|
||||
return recursiveCalcOfDividerSum(number, div);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
200
Maths/Area.java
200
Maths/Area.java
@ -1,119 +1,117 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* Find the area of various geometric shapes
|
||||
*/
|
||||
/** Find the area of various geometric shapes */
|
||||
public class Area {
|
||||
public static void main(String[] args) {
|
||||
|
||||
/* test cube */
|
||||
assert Double.compare(surfaceAreaCube(1), 6.0) == 0;
|
||||
public static void main(String[] args) {
|
||||
|
||||
/* test sphere */
|
||||
assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0;
|
||||
assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0;
|
||||
/* test cube */
|
||||
assert Double.compare(surfaceAreaCube(1), 6.0) == 0;
|
||||
|
||||
/* test rectangle */
|
||||
assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0;
|
||||
/* test sphere */
|
||||
assert Double.compare(surfaceAreaSphere(5), 314.1592653589793) == 0;
|
||||
assert Double.compare(surfaceAreaSphere(1), 12.566370614359172) == 0;
|
||||
|
||||
/* test square */
|
||||
assert Double.compare(surfaceAreaSquare(10), 100.0) == 0;
|
||||
/* test rectangle */
|
||||
assert Double.compare(surfaceAreaRectangle(10, 20), 200.0) == 0;
|
||||
|
||||
/* test triangle */
|
||||
assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0;
|
||||
/* test square */
|
||||
assert Double.compare(surfaceAreaSquare(10), 100.0) == 0;
|
||||
|
||||
/* test parallelogram */
|
||||
assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0;
|
||||
/* test triangle */
|
||||
assert Double.compare(surfaceAreaTriangle(10, 10), 50.0) == 0;
|
||||
|
||||
/* test trapezium */
|
||||
assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0;
|
||||
/* test parallelogram */
|
||||
assert Double.compare(surfaceAreaParallelogram(10, 20), 200.0) == 0;
|
||||
|
||||
/* test circle */
|
||||
assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0;
|
||||
}
|
||||
/* test trapezium */
|
||||
assert Double.compare(surfaceAreaTrapezium(10, 20, 30), 450.0) == 0;
|
||||
|
||||
/**
|
||||
* Calculate the surface area of a cube.
|
||||
*
|
||||
* @param sideLength side length of cube
|
||||
* @return surface area of given cube
|
||||
*/
|
||||
private static double surfaceAreaCube(double sideLength) {
|
||||
return 6 * sideLength * sideLength;
|
||||
}
|
||||
/* test circle */
|
||||
assert Double.compare(surfaceAreaCircle(20), 1256.6370614359173) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the surface area of a sphere.
|
||||
*
|
||||
* @param radius radius of sphere
|
||||
* @return surface area of given sphere
|
||||
*/
|
||||
private static double surfaceAreaSphere(double radius) {
|
||||
return 4 * Math.PI * radius * radius;
|
||||
}
|
||||
/**
|
||||
* Calculate the surface area of a cube.
|
||||
*
|
||||
* @param sideLength side length of cube
|
||||
* @return surface area of given cube
|
||||
*/
|
||||
private static double surfaceAreaCube(double sideLength) {
|
||||
return 6 * sideLength * sideLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a rectangle
|
||||
*
|
||||
* @param length length of rectangle
|
||||
* @param width width of rectangle
|
||||
* @return area of given rectangle
|
||||
*/
|
||||
private static double surfaceAreaRectangle(double length, double width) {
|
||||
return length * width;
|
||||
}
|
||||
/**
|
||||
* Calculate the surface area of a sphere.
|
||||
*
|
||||
* @param radius radius of sphere
|
||||
* @return surface area of given sphere
|
||||
*/
|
||||
private static double surfaceAreaSphere(double radius) {
|
||||
return 4 * Math.PI * radius * radius;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a square
|
||||
*
|
||||
* @param sideLength side length of square
|
||||
* @return area of given square
|
||||
*/
|
||||
private static double surfaceAreaSquare(double sideLength) {
|
||||
return sideLength * sideLength;
|
||||
}
|
||||
/**
|
||||
* Calculate the area of a rectangle
|
||||
*
|
||||
* @param length length of rectangle
|
||||
* @param width width of rectangle
|
||||
* @return area of given rectangle
|
||||
*/
|
||||
private static double surfaceAreaRectangle(double length, double width) {
|
||||
return length * width;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a triangle
|
||||
*
|
||||
* @param base base of triangle
|
||||
* @param height height of triangle
|
||||
* @return area of given triangle
|
||||
*/
|
||||
private static double surfaceAreaTriangle(double base, double height) {
|
||||
return base * height / 2;
|
||||
}
|
||||
/**
|
||||
* Calculate the area of a square
|
||||
*
|
||||
* @param sideLength side length of square
|
||||
* @return area of given square
|
||||
*/
|
||||
private static double surfaceAreaSquare(double sideLength) {
|
||||
return sideLength * sideLength;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a parallelogram
|
||||
*
|
||||
* @param base base of parallelogram
|
||||
* @param height height of parallelogram
|
||||
* @return area of given parallelogram
|
||||
*/
|
||||
private static double surfaceAreaParallelogram(double base, double height) {
|
||||
return base * height;
|
||||
}
|
||||
/**
|
||||
* Calculate the area of a triangle
|
||||
*
|
||||
* @param base base of triangle
|
||||
* @param height height of triangle
|
||||
* @return area of given triangle
|
||||
*/
|
||||
private static double surfaceAreaTriangle(double base, double height) {
|
||||
return base * height / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a trapezium
|
||||
*
|
||||
* @param base1 upper base of trapezium
|
||||
* @param base2 bottom base of trapezium
|
||||
* @param height height of trapezium
|
||||
* @return area of given trapezium
|
||||
*/
|
||||
private static double surfaceAreaTrapezium(double base1, double base2, double height) {
|
||||
return (base1 + base2) * height / 2;
|
||||
}
|
||||
/**
|
||||
* Calculate the area of a parallelogram
|
||||
*
|
||||
* @param base base of parallelogram
|
||||
* @param height height of parallelogram
|
||||
* @return area of given parallelogram
|
||||
*/
|
||||
private static double surfaceAreaParallelogram(double base, double height) {
|
||||
return base * height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a circle
|
||||
*
|
||||
* @param radius radius of circle
|
||||
* @return area of given circle
|
||||
*/
|
||||
private static double surfaceAreaCircle(double radius) {
|
||||
return Math.PI * radius * radius;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Calculate the area of a trapezium
|
||||
*
|
||||
* @param base1 upper base of trapezium
|
||||
* @param base2 bottom base of trapezium
|
||||
* @param height height of trapezium
|
||||
* @return area of given trapezium
|
||||
*/
|
||||
private static double surfaceAreaTrapezium(double base1, double base2, double height) {
|
||||
return (base1 + base2) * height / 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the area of a circle
|
||||
*
|
||||
* @param radius radius of circle
|
||||
* @return area of given circle
|
||||
*/
|
||||
private static double surfaceAreaCircle(double radius) {
|
||||
return Math.PI * radius * radius;
|
||||
}
|
||||
}
|
||||
|
@ -1,43 +1,44 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* An Armstrong number is equal to the sum of the cubes of its digits.
|
||||
* For example, 370 is an Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370.
|
||||
* An Armstrong number is often called Narcissistic number.
|
||||
* An Armstrong number is equal to the sum of the cubes of its digits. For example, 370 is an
|
||||
* Armstrong number because 3*3*3 + 7*7*7 + 0*0*0 = 370. An Armstrong number is often called
|
||||
* Narcissistic number.
|
||||
*/
|
||||
public class Armstrong {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert (isArmStrong(0));
|
||||
assert (isArmStrong(1));
|
||||
assert (isArmStrong(153));
|
||||
assert (isArmStrong(1634));
|
||||
assert (isArmStrong(371));
|
||||
assert (!isArmStrong(200));
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert (isArmStrong(0));
|
||||
assert (isArmStrong(1));
|
||||
assert (isArmStrong(153));
|
||||
assert (isArmStrong(1634));
|
||||
assert (isArmStrong(371));
|
||||
assert (!isArmStrong(200));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a given number is an armstrong number or not.
|
||||
*
|
||||
* @param number number to check
|
||||
* @return {@code true} if given number is armstrong number, {@code false} otherwise
|
||||
*/
|
||||
private static boolean isArmStrong(int number) {
|
||||
int sum = 0;
|
||||
int temp = number;
|
||||
int numberOfDigits = 0;
|
||||
while (temp != 0) {
|
||||
numberOfDigits++;
|
||||
temp /= 10;
|
||||
}
|
||||
temp = number; /* copy number again */
|
||||
while (number > 0) {
|
||||
int remainder = number % 10;
|
||||
int power = 1;
|
||||
for (int i = 1; i <= numberOfDigits; power *= remainder, ++i) ;
|
||||
sum = sum + power;
|
||||
number /= 10;
|
||||
}
|
||||
return sum == temp;
|
||||
/**
|
||||
* Checks whether a given number is an armstrong number or not.
|
||||
*
|
||||
* @param number number to check
|
||||
* @return {@code true} if given number is armstrong number, {@code false} otherwise
|
||||
*/
|
||||
private static boolean isArmStrong(int number) {
|
||||
int sum = 0;
|
||||
int temp = number;
|
||||
int numberOfDigits = 0;
|
||||
while (temp != 0) {
|
||||
numberOfDigits++;
|
||||
temp /= 10;
|
||||
}
|
||||
temp = number; /* copy number again */
|
||||
while (number > 0) {
|
||||
int remainder = number % 10;
|
||||
int power = 1;
|
||||
for (int i = 1; i <= numberOfDigits; power *= remainder, ++i)
|
||||
;
|
||||
sum = sum + power;
|
||||
number /= 10;
|
||||
}
|
||||
return sum == temp;
|
||||
}
|
||||
}
|
||||
|
@ -1,44 +1,42 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* Calculate average of a list of numbers
|
||||
*/
|
||||
/** Calculate average of a list of numbers */
|
||||
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 average(array) == 5;
|
||||
}
|
||||
private static final double SMALL_VALUE = 0.00001f;
|
||||
|
||||
/**
|
||||
* Calculate average of a list of numbers
|
||||
*
|
||||
* @param numbers array to store numbers
|
||||
* @return mean of given numbers
|
||||
*/
|
||||
public static double average(double[] numbers) {
|
||||
double sum = 0;
|
||||
for (double number : numbers) {
|
||||
sum += number;
|
||||
}
|
||||
return sum / numbers.length;
|
||||
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 average(array) == 5;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate average of a list of numbers
|
||||
*
|
||||
* @param numbers array to store numbers
|
||||
* @return mean of given numbers
|
||||
*/
|
||||
public static double average(double[] numbers) {
|
||||
double sum = 0;
|
||||
for (double number : numbers) {
|
||||
sum += number;
|
||||
}
|
||||
|
||||
/**
|
||||
* find average value of int array
|
||||
*
|
||||
* @param array the array contains element and the sum does not
|
||||
* excess long value limit
|
||||
* @return average value
|
||||
*/
|
||||
public static int average(int[] array) {
|
||||
long sum = 0;
|
||||
for (int i = 0 ; i < array.length; ++i) {
|
||||
sum += array[i];
|
||||
}
|
||||
return (int)(sum / array.length);
|
||||
return sum / numbers.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* find average value of int array
|
||||
*
|
||||
* @param array the array contains element and the sum does not excess long value limit
|
||||
* @return average value
|
||||
*/
|
||||
public static int average(int[] array) {
|
||||
long sum = 0;
|
||||
for (int i = 0; i < array.length; ++i) {
|
||||
sum += array[i];
|
||||
}
|
||||
}
|
||||
return (int) (sum / array.length);
|
||||
}
|
||||
}
|
||||
|
@ -3,27 +3,27 @@ package Maths;
|
||||
import java.util.Random;
|
||||
|
||||
public class Ceil {
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
double randomNumber = random.nextDouble();
|
||||
assert ceil(randomNumber) == Math.ceil(randomNumber);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
double randomNumber = random.nextDouble();
|
||||
assert ceil(randomNumber) == Math.ceil(randomNumber);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the smallest (closest to negative infinity)
|
||||
*
|
||||
* @param number the number
|
||||
* @return the smallest (closest to negative infinity) of given {@code number}
|
||||
*/
|
||||
public static double ceil(double number) {
|
||||
if (number - (int) number == 0) {
|
||||
return number;
|
||||
} else if (number - (int) number > 0) {
|
||||
return (int) (number + 1);
|
||||
} else {
|
||||
return (int) number;
|
||||
}
|
||||
/**
|
||||
* Returns the smallest (closest to negative infinity)
|
||||
*
|
||||
* @param number the number
|
||||
* @return the smallest (closest to negative infinity) of given {@code number}
|
||||
*/
|
||||
public static double ceil(double number) {
|
||||
if (number - (int) number == 0) {
|
||||
return number;
|
||||
} else if (number - (int) number > 0) {
|
||||
return (int) (number + 1);
|
||||
} else {
|
||||
return (int) number;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,37 +1,35 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a>
|
||||
*/
|
||||
/** @see <a href="https://en.wikipedia.org/wiki/Combination">Combination</a> */
|
||||
public class Combinations {
|
||||
public static void main(String[] args) {
|
||||
assert combinations(1, 1) == 1;
|
||||
assert combinations(10, 5) == 252;
|
||||
assert combinations(6, 3) == 20;
|
||||
assert combinations(20, 5) == 15504;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert combinations(1, 1) == 1;
|
||||
assert combinations(10, 5) == 252;
|
||||
assert combinations(6, 3) == 20;
|
||||
assert combinations(20, 5) == 15504;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate of factorial
|
||||
*
|
||||
* @param n the number
|
||||
* @return factorial of given number
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
|
||||
/**
|
||||
* Calculate of factorial
|
||||
*
|
||||
* @param n the number
|
||||
* @return factorial of given number
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate combinations
|
||||
*
|
||||
* @param n first number
|
||||
* @param k second number
|
||||
* @return combinations of given {@code n} and {@code k}
|
||||
*/
|
||||
public static long combinations(int n, int k) {
|
||||
return factorial(n) / (factorial(k) * factorial(n - k));
|
||||
}
|
||||
/**
|
||||
* Calculate combinations
|
||||
*
|
||||
* @param n first number
|
||||
* @param k second number
|
||||
* @return combinations of given {@code n} and {@code k}
|
||||
*/
|
||||
public static long combinations(int n, int k) {
|
||||
return factorial(n) / (factorial(k) * factorial(n - k));
|
||||
}
|
||||
}
|
||||
|
@ -2,26 +2,27 @@ package Maths;
|
||||
|
||||
public class Factorial {
|
||||
|
||||
/* Driver Code */
|
||||
public static void main(String[] args) {
|
||||
assert factorial(0) == 1;
|
||||
assert factorial(1) == 1;
|
||||
assert factorial(5) == 120;
|
||||
assert factorial(10) == 3628800;
|
||||
}
|
||||
/* Driver Code */
|
||||
public static void main(String[] args) {
|
||||
assert factorial(0) == 1;
|
||||
assert factorial(1) == 1;
|
||||
assert factorial(5) == 120;
|
||||
assert factorial(10) == 3628800;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate factorial N using iteration
|
||||
*
|
||||
* @param n the number
|
||||
* @return the factorial of {@code n}
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
long factorial = 1;
|
||||
for (int i = 1; i <= n; factorial *= i, ++i) ;
|
||||
return factorial;
|
||||
/**
|
||||
* Calculate factorial N using iteration
|
||||
*
|
||||
* @param n the number
|
||||
* @return the factorial of {@code n}
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
long factorial = 1;
|
||||
for (int i = 1; i <= n; factorial *= i, ++i)
|
||||
;
|
||||
return factorial;
|
||||
}
|
||||
}
|
||||
|
@ -2,25 +2,25 @@ package Maths;
|
||||
|
||||
public class FactorialRecursion {
|
||||
|
||||
/* Driver Code */
|
||||
public static void main(String[] args) {
|
||||
assert factorial(0) == 1;
|
||||
assert factorial(1) == 1;
|
||||
assert factorial(2) == 2;
|
||||
assert factorial(3) == 6;
|
||||
assert factorial(5) == 120;
|
||||
}
|
||||
/* Driver Code */
|
||||
public static void main(String[] args) {
|
||||
assert factorial(0) == 1;
|
||||
assert factorial(1) == 1;
|
||||
assert factorial(2) == 2;
|
||||
assert factorial(3) == 6;
|
||||
assert factorial(5) == 120;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursive FactorialRecursion Method
|
||||
*
|
||||
* @param n The number to factorial
|
||||
* @return The factorial of the number
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
|
||||
/**
|
||||
* Recursive FactorialRecursion Method
|
||||
*
|
||||
* @param n The number to factorial
|
||||
* @return The factorial of the number
|
||||
*/
|
||||
public static long factorial(int n) {
|
||||
if (n < 0) {
|
||||
throw new IllegalArgumentException("number is negative");
|
||||
}
|
||||
return n == 0 || n == 1 ? 1 : n * factorial(n - 1);
|
||||
}
|
||||
}
|
||||
|
@ -1,37 +1,35 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* Fibonacci: 0 1 1 2 3 5 8 13 21 ...
|
||||
*/
|
||||
/** Fibonacci: 0 1 1 2 3 5 8 13 21 ... */
|
||||
public class FibonacciNumber {
|
||||
public static void main(String[] args) {
|
||||
assert isFibonacciNumber(1);
|
||||
assert isFibonacciNumber(2);
|
||||
assert isFibonacciNumber(21);
|
||||
assert !isFibonacciNumber(9);
|
||||
assert !isFibonacciNumber(10);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert isFibonacciNumber(1);
|
||||
assert isFibonacciNumber(2);
|
||||
assert isFibonacciNumber(21);
|
||||
assert !isFibonacciNumber(9);
|
||||
assert !isFibonacciNumber(10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is perfect square number
|
||||
*
|
||||
* @param number the number to be checked
|
||||
* @return <tt>true</tt> if {@code number} is perfect square, otherwise <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPerfectSquare(int number) {
|
||||
int sqrt = (int) Math.sqrt(number);
|
||||
return sqrt * sqrt == number;
|
||||
}
|
||||
/**
|
||||
* Check if a number is perfect square number
|
||||
*
|
||||
* @param number the number to be checked
|
||||
* @return <tt>true</tt> if {@code number} is perfect square, otherwise <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPerfectSquare(int number) {
|
||||
int sqrt = (int) Math.sqrt(number);
|
||||
return sqrt * sqrt == number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is fibonacci number
|
||||
* This is true if and only if at least one of 5x^2+4 or 5x^2-4 is a perfect square
|
||||
*
|
||||
* @param number the number
|
||||
* @return <tt>true</tt> if {@code number} is fibonacci number, otherwise <tt>false</tt>
|
||||
* @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);
|
||||
}
|
||||
/**
|
||||
* Check if a number is fibonacci number This is true if and only if at least one of 5x^2+4 or
|
||||
* 5x^2-4 is a perfect square
|
||||
*
|
||||
* @param number the number
|
||||
* @return <tt>true</tt> if {@code number} is fibonacci number, otherwise <tt>false</tt>
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
@ -5,37 +5,35 @@ import java.util.Random;
|
||||
|
||||
public class FindMax {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
/** Driver Code */
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
|
||||
/* random size */
|
||||
int size = random.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
/* random size */
|
||||
int size = random.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
|
||||
/* init array with random numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = random.nextInt() % 100;
|
||||
}
|
||||
|
||||
assert Arrays.stream(array).max().getAsInt() == findMax(array);
|
||||
/* init array with random numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = random.nextInt() % 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* find max of array
|
||||
*
|
||||
* @param array the array contains element
|
||||
* @return max value of given array
|
||||
*/
|
||||
public static int findMax(int[] array) {
|
||||
int max = array[0];
|
||||
for (int i = 1; i < array.length; ++i) {
|
||||
if (array[i] > max) {
|
||||
max = array[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
assert Arrays.stream(array).max().getAsInt() == findMax(array);
|
||||
}
|
||||
|
||||
/**
|
||||
* find max of array
|
||||
*
|
||||
* @param array the array contains element
|
||||
* @return max value of given array
|
||||
*/
|
||||
public static int findMax(int[] array) {
|
||||
int max = array[0];
|
||||
for (int i = 1; i < array.length; ++i) {
|
||||
if (array[i] > max) {
|
||||
max = array[i];
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
}
|
||||
|
@ -4,51 +4,51 @@ import java.util.Arrays;
|
||||
import java.util.Random;
|
||||
|
||||
public class FindMaxRecursion {
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
|
||||
/* rand size */
|
||||
int size = rand.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
/* rand size */
|
||||
int size = rand.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
|
||||
/* init array with rand numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
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();
|
||||
/* init array with rand numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = rand.nextInt() % 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get max of array using divide and conquer algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param low the index of the first element
|
||||
* @param high the index of the last element
|
||||
* @return max of {@code array}
|
||||
*/
|
||||
public static int max(int[] array, int low, int high) {
|
||||
if (low == high) {
|
||||
return array[low]; //or array[high]
|
||||
}
|
||||
assert max(array, array.length) == Arrays.stream(array).max().getAsInt();
|
||||
assert max(array, 0, array.length - 1) == Arrays.stream(array).max().getAsInt();
|
||||
}
|
||||
|
||||
int mid = (low + high) >>> 1;
|
||||
|
||||
int leftMax = max(array, low, mid); //get max in [low, mid]
|
||||
int rightMax = max(array, mid + 1, high); //get max in [mid+1, high]
|
||||
|
||||
return Math.max(leftMax, rightMax);
|
||||
/**
|
||||
* Get max of array using divide and conquer algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param low the index of the first element
|
||||
* @param high the index of the last element
|
||||
* @return max of {@code array}
|
||||
*/
|
||||
public static int max(int[] array, int low, int high) {
|
||||
if (low == high) {
|
||||
return array[low]; // or array[high]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get max of array using recursion algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param len length of given array
|
||||
* @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]);
|
||||
}
|
||||
int mid = (low + high) >>> 1;
|
||||
|
||||
int leftMax = max(array, low, mid); // get max in [low, mid]
|
||||
int rightMax = max(array, mid + 1, high); // get max in [mid+1, high]
|
||||
|
||||
return Math.max(leftMax, rightMax);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get max of array using recursion algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param len length of given array
|
||||
* @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]);
|
||||
}
|
||||
}
|
||||
|
@ -5,37 +5,35 @@ import java.util.Random;
|
||||
|
||||
public class FindMin {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
/** Driver Code */
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
|
||||
/* random size */
|
||||
int size = random.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
/* random size */
|
||||
int size = random.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
|
||||
/* init array with random numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = random.nextInt() % 100;
|
||||
}
|
||||
|
||||
assert Arrays.stream(array).min().getAsInt() == findMin(array);
|
||||
/* init array with random numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = random.nextInt() % 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the minimum number of an array of numbers.
|
||||
*
|
||||
* @param array the array contains element
|
||||
* @return min value
|
||||
*/
|
||||
public static int findMin(int[] array) {
|
||||
int min = array[0];
|
||||
for (int i = 1; i < array.length; ++i) {
|
||||
if (array[i] < min) {
|
||||
min = array[i];
|
||||
}
|
||||
}
|
||||
return min;
|
||||
assert Arrays.stream(array).min().getAsInt() == findMin(array);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the minimum number of an array of numbers.
|
||||
*
|
||||
* @param array the array contains element
|
||||
* @return min value
|
||||
*/
|
||||
public static int findMin(int[] array) {
|
||||
int min = array[0];
|
||||
for (int i = 1; i < array.length; ++i) {
|
||||
if (array[i] < min) {
|
||||
min = array[i];
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
}
|
||||
|
@ -5,54 +5,52 @@ import java.util.Random;
|
||||
|
||||
public class FindMinRecursion {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
/** Driver Code */
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
|
||||
/* rand size */
|
||||
int size = rand.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
/* rand size */
|
||||
int size = rand.nextInt(100) + 1;
|
||||
int[] array = new int[size];
|
||||
|
||||
/* init array with rand numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
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();
|
||||
/* init array with rand numbers */
|
||||
for (int i = 0; i < size; i++) {
|
||||
array[i] = rand.nextInt() % 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get min of array using divide and conquer algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param low the index of the first element
|
||||
* @param high the index of the last element
|
||||
* @return min of {@code array}
|
||||
*/
|
||||
public static int min(int[] array, int low, int high) {
|
||||
if (low == high) {
|
||||
return array[low]; //or array[high]
|
||||
}
|
||||
assert min(array, 0, array.length - 1) == Arrays.stream(array).min().getAsInt();
|
||||
assert min(array, array.length) == Arrays.stream(array).min().getAsInt();
|
||||
}
|
||||
|
||||
int mid = (low + high) >>> 1;
|
||||
|
||||
int leftMin = min(array, low, mid); //get min in [low, mid]
|
||||
int rightMin = min(array, mid + 1, high); //get min in [mid+1, high]
|
||||
|
||||
return Math.min(leftMin, rightMin);
|
||||
/**
|
||||
* Get min of array using divide and conquer algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param low the index of the first element
|
||||
* @param high the index of the last element
|
||||
* @return min of {@code array}
|
||||
*/
|
||||
public static int min(int[] array, int low, int high) {
|
||||
if (low == high) {
|
||||
return array[low]; // or array[high]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get min of array using recursion algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param len length of given array
|
||||
* @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]);
|
||||
}
|
||||
int mid = (low + high) >>> 1;
|
||||
|
||||
int leftMin = min(array, low, mid); // get min in [low, mid]
|
||||
int rightMin = min(array, mid + 1, high); // get min in [mid+1, high]
|
||||
|
||||
return Math.min(leftMin, rightMin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get min of array using recursion algorithm
|
||||
*
|
||||
* @param array contains elements
|
||||
* @param len length of given array
|
||||
* @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]);
|
||||
}
|
||||
}
|
||||
|
@ -3,27 +3,27 @@ package Maths;
|
||||
import java.util.Random;
|
||||
|
||||
public class Floor {
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
double randomNumber = random.nextDouble();
|
||||
assert floor(randomNumber) == Math.floor(randomNumber);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Random random = new Random();
|
||||
for (int i = 1; i <= 1000; ++i) {
|
||||
double randomNumber = random.nextDouble();
|
||||
assert floor(randomNumber) == Math.floor(randomNumber);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the largest (closest to positive infinity)
|
||||
*
|
||||
* @param number the number
|
||||
* @return the largest (closest to positive infinity) of given {@code number}
|
||||
*/
|
||||
public static double floor(double number) {
|
||||
if (number - (int) number == 0) {
|
||||
return number;
|
||||
} else if (number - (int) number > 0) {
|
||||
return (int) number;
|
||||
} else {
|
||||
return (int) number - 1;
|
||||
}
|
||||
/**
|
||||
* Returns the largest (closest to positive infinity)
|
||||
*
|
||||
* @param number the number
|
||||
* @return the largest (closest to positive infinity) of given {@code number}
|
||||
*/
|
||||
public static double floor(double number) {
|
||||
if (number - (int) number == 0) {
|
||||
return number;
|
||||
} else if (number - (int) number > 0) {
|
||||
return (int) number;
|
||||
} else {
|
||||
return (int) number - 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,57 +1,57 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* This is Euclid's algorithm which is used to find the greatest common denominator
|
||||
* Overide function name gcd
|
||||
* This is Euclid's algorithm which is used to find the greatest common denominator Overide function
|
||||
* name gcd
|
||||
*
|
||||
* @author Oskar Enmalm 3/10/17
|
||||
*/
|
||||
public class GCD {
|
||||
|
||||
/**
|
||||
* get greatest common divisor
|
||||
*
|
||||
* @param num1 the first number
|
||||
* @param num2 the second number
|
||||
* @return gcd
|
||||
*/
|
||||
public static int gcd(int num1, int num2) {
|
||||
if (num1 < 0 || num2 < 0) {
|
||||
throw new ArithmeticException();
|
||||
}
|
||||
|
||||
if (num1 == 0 || num2 == 0) {
|
||||
return Math.abs(num1 - num2);
|
||||
}
|
||||
|
||||
while (num1 % num2 != 0) {
|
||||
int remainder = num1 % num2;
|
||||
num1 = num2;
|
||||
num2 = remainder;
|
||||
}
|
||||
return num2;
|
||||
/**
|
||||
* get greatest common divisor
|
||||
*
|
||||
* @param num1 the first number
|
||||
* @param num2 the second number
|
||||
* @return gcd
|
||||
*/
|
||||
public static int gcd(int num1, int num2) {
|
||||
if (num1 < 0 || num2 < 0) {
|
||||
throw new ArithmeticException();
|
||||
}
|
||||
|
||||
/**
|
||||
* get greatest common divisor in array
|
||||
*
|
||||
* @param number contains number
|
||||
* @return 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)
|
||||
result = gcd(result, number[i]);
|
||||
|
||||
return result;
|
||||
if (num1 == 0 || num2 == 0) {
|
||||
return Math.abs(num1 - num2);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
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
|
||||
while (num1 % num2 != 0) {
|
||||
int remainder = num1 % num2;
|
||||
num1 = num2;
|
||||
num2 = remainder;
|
||||
}
|
||||
return num2;
|
||||
}
|
||||
|
||||
/**
|
||||
* get greatest common divisor in array
|
||||
*
|
||||
* @param number contains number
|
||||
* @return 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)
|
||||
result = gcd(result, number[i]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
@ -1,36 +1,34 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* @author https://github.com/shellhub/
|
||||
*/
|
||||
/** @author https://github.com/shellhub/ */
|
||||
public class GCDRecursion {
|
||||
public static void main(String[] args) {
|
||||
System.out.println(gcd(20, 15)); /* output: 5 */
|
||||
System.out.println(gcd(10, 8)); /* output: 2 */
|
||||
System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */
|
||||
public static void main(String[] args) {
|
||||
System.out.println(gcd(20, 15)); /* output: 5 */
|
||||
System.out.println(gcd(10, 8)); /* output: 2 */
|
||||
System.out.println(gcd(gcd(10, 5), gcd(5, 10))); /* output: 5 */
|
||||
}
|
||||
|
||||
/**
|
||||
* get greatest common divisor
|
||||
*
|
||||
* @param a the first number
|
||||
* @param b the second number
|
||||
* @return gcd
|
||||
*/
|
||||
public static int gcd(int a, int b) {
|
||||
|
||||
if (a < 0 || b < 0) {
|
||||
throw new ArithmeticException();
|
||||
}
|
||||
|
||||
/**
|
||||
* get greatest common divisor
|
||||
*
|
||||
* @param a the first number
|
||||
* @param b the second number
|
||||
* @return gcd
|
||||
*/
|
||||
public static int gcd(int a, int b) {
|
||||
|
||||
if (a < 0 || b < 0) {
|
||||
throw new ArithmeticException();
|
||||
}
|
||||
|
||||
if (a == 0 || b == 0) {
|
||||
return Math.abs(a - b);
|
||||
}
|
||||
|
||||
if (a % b == 0) {
|
||||
return b;
|
||||
} else {
|
||||
return gcd(b, a % b);
|
||||
}
|
||||
if (a == 0 || b == 0) {
|
||||
return Math.abs(a - b);
|
||||
}
|
||||
|
||||
if (a % b == 0) {
|
||||
return b;
|
||||
} else {
|
||||
return gcd(b, a % b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,44 +1,43 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* https://en.wikipedia.org/wiki/Lucas_number
|
||||
*/
|
||||
/** https://en.wikipedia.org/wiki/Lucas_number */
|
||||
public class LucasSeries {
|
||||
public static void main(String[] args) {
|
||||
assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
|
||||
assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1;
|
||||
assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3;
|
||||
assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4;
|
||||
assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
|
||||
assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
|
||||
assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
|
||||
public static void main(String[] args) {
|
||||
assert lucasSeries(1) == 2 && lucasSeriesIteration(1) == 2;
|
||||
assert lucasSeries(2) == 1 && lucasSeriesIteration(2) == 1;
|
||||
assert lucasSeries(3) == 3 && lucasSeriesIteration(3) == 3;
|
||||
assert lucasSeries(4) == 4 && lucasSeriesIteration(4) == 4;
|
||||
assert lucasSeries(5) == 7 && lucasSeriesIteration(5) == 7;
|
||||
assert lucasSeries(6) == 11 && lucasSeriesIteration(6) == 11;
|
||||
assert lucasSeries(11) == 123 && lucasSeriesIteration(11) == 123;
|
||||
}
|
||||
|
||||
}
|
||||
/**
|
||||
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
|
||||
* recursion
|
||||
*
|
||||
* @param n nth
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using recursion
|
||||
*
|
||||
* @param n nth
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using iteration
|
||||
*
|
||||
* @param n nth
|
||||
* @return nth number of lucas series
|
||||
*/
|
||||
public static int lucasSeriesIteration(int n) {
|
||||
int previous = 2;
|
||||
int current = 1;
|
||||
for (int i = 1; i < n; i++) {
|
||||
int next = previous + current;
|
||||
previous = current;
|
||||
current = next;
|
||||
}
|
||||
return previous;
|
||||
/**
|
||||
* Calculate nth number of lucas series(2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, ....) using
|
||||
* iteration
|
||||
*
|
||||
* @param n nth
|
||||
* @return nth number of lucas series
|
||||
*/
|
||||
public static int lucasSeriesIteration(int n) {
|
||||
int previous = 2;
|
||||
int current = 1;
|
||||
for (int i = 1; i < n; i++) {
|
||||
int next = previous + current;
|
||||
previous = current;
|
||||
current = next;
|
||||
}
|
||||
return previous;
|
||||
}
|
||||
}
|
||||
|
@ -4,32 +4,29 @@ import java.util.Random;
|
||||
|
||||
public class MaxValue {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
/** Driver Code */
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
|
||||
/* test 100 times using rand numbers */
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
/* generate number from -50 to 49 */
|
||||
int a = rand.nextInt(100) - 50;
|
||||
int b = rand.nextInt(100) - 50;
|
||||
assert max(a, b) == Math.max(a, b);
|
||||
}
|
||||
/* test 100 times using rand numbers */
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
/* generate number from -50 to 49 */
|
||||
int a = rand.nextInt(100) - 50;
|
||||
int b = rand.nextInt(100) - 50;
|
||||
assert max(a, b) == Math.max(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the greater of two {@code int} values. That is, the
|
||||
* result is the argument closer to the value of
|
||||
* {@link Integer#MAX_VALUE}. If the arguments have the same value,
|
||||
* the result is that same value.
|
||||
*
|
||||
* @param a an argument.
|
||||
* @param b another argument.
|
||||
* @return the larger of {@code a} and {@code b}.
|
||||
*/
|
||||
public static int max(int a, int b) {
|
||||
return a >= b ? a : b;
|
||||
}
|
||||
/**
|
||||
* Returns the greater of two {@code int} values. That is, the result is the argument closer to
|
||||
* the value of {@link Integer#MAX_VALUE}. If the arguments have the same value, the result is
|
||||
* that same value.
|
||||
*
|
||||
* @param a an argument.
|
||||
* @param b another argument.
|
||||
* @return the larger of {@code a} and {@code b}.
|
||||
*/
|
||||
public static int max(int a, int b) {
|
||||
return a >= b ? a : b;
|
||||
}
|
||||
}
|
||||
|
@ -2,27 +2,27 @@ package Maths;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Wikipedia: https://en.wikipedia.org/wiki/Median
|
||||
*/
|
||||
/** Wikipedia: https://en.wikipedia.org/wiki/Median */
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate average median
|
||||
*
|
||||
* @param values number series
|
||||
* @return median of given {@code values}
|
||||
*/
|
||||
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];
|
||||
}
|
||||
/**
|
||||
* Calculate average median
|
||||
*
|
||||
* @param values number series
|
||||
* @return median of given {@code values}
|
||||
*/
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
@ -4,32 +4,29 @@ import java.util.Random;
|
||||
|
||||
public class MinValue {
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
/** Driver Code */
|
||||
public static void main(String[] args) {
|
||||
Random rand = new Random();
|
||||
|
||||
/* test 100 times using rand numbers */
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
/* generate number from -50 to 49 */
|
||||
int a = rand.nextInt(100) - 50;
|
||||
int b = rand.nextInt(100) - 50;
|
||||
assert min(a, b) == Math.min(a, b);
|
||||
}
|
||||
/* test 100 times using rand numbers */
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
/* generate number from -50 to 49 */
|
||||
int a = rand.nextInt(100) - 50;
|
||||
int b = rand.nextInt(100) - 50;
|
||||
assert min(a, b) == Math.min(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the smaller of two {@code int} values. That is,
|
||||
* the result the argument closer to the value of
|
||||
* {@link Integer#MIN_VALUE}. If the arguments have the same
|
||||
* value, the result is that same value.
|
||||
*
|
||||
* @param a an argument.
|
||||
* @param b another argument.
|
||||
* @return the smaller of {@code a} and {@code b}.
|
||||
*/
|
||||
public static int min(int a, int b) {
|
||||
return a <= b ? a : b;
|
||||
}
|
||||
/**
|
||||
* Returns the smaller of two {@code int} values. That is, the result the argument closer to the
|
||||
* value of {@link Integer#MIN_VALUE}. If the arguments have the same value, the result is that
|
||||
* same value.
|
||||
*
|
||||
* @param a an argument.
|
||||
* @param b another argument.
|
||||
* @return the smaller of {@code a} and {@code b}.
|
||||
*/
|
||||
public static int min(int a, int b) {
|
||||
return a <= b ? a : b;
|
||||
}
|
||||
}
|
||||
|
@ -7,57 +7,53 @@ import java.util.HashMap;
|
||||
|
||||
/*
|
||||
* Find the mode of an array of numbers
|
||||
*
|
||||
* The mode of an array of numbers is the most frequently occurring number in the array,
|
||||
*
|
||||
* The mode of an array of numbers is the most frequently occurring number in the array,
|
||||
* or the most frequently occurring numbers if there are multiple numbers with the same frequency
|
||||
*/
|
||||
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});
|
||||
|
||||
}
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
HashMap<Integer, Integer> count = new HashMap<>();
|
||||
|
||||
for(int num : numbers) {
|
||||
if(count.containsKey(num)) {
|
||||
|
||||
count.put(num, count.get(num) + 1);
|
||||
|
||||
} else {
|
||||
|
||||
count.put(num, 1);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int max = Collections.max(count.values());
|
||||
ArrayList<Integer> modes = new ArrayList<>();
|
||||
|
||||
for(int num : count.keySet()) {
|
||||
if(count.get(num) == max) {
|
||||
modes.add(num);
|
||||
}
|
||||
}
|
||||
return modes.stream().mapToInt(n -> n).toArray();
|
||||
}
|
||||
|
||||
|
||||
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});
|
||||
}
|
||||
|
||||
/*
|
||||
* 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;
|
||||
|
||||
HashMap<Integer, Integer> count = new HashMap<>();
|
||||
|
||||
for (int num : numbers) {
|
||||
if (count.containsKey(num)) {
|
||||
|
||||
count.put(num, count.get(num) + 1);
|
||||
|
||||
} else {
|
||||
|
||||
count.put(num, 1);
|
||||
}
|
||||
}
|
||||
|
||||
int max = Collections.max(count.values());
|
||||
ArrayList<Integer> modes = new ArrayList<>();
|
||||
|
||||
for (int num : count.keySet()) {
|
||||
if (count.get(num) == max) {
|
||||
modes.add(num);
|
||||
}
|
||||
}
|
||||
return modes.stream().mapToInt(n -> n).toArray();
|
||||
}
|
||||
}
|
||||
|
@ -1,62 +1,59 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number.
|
||||
*/
|
||||
/** Find the number of digits in a number. */
|
||||
public class NumberOfDigits {
|
||||
public static void main(String[] args) {
|
||||
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;
|
||||
assert numberOfDigitsFaster(numbers[i]) == i + 1;
|
||||
assert numberOfDigitsRecursion(numbers[i]) == i + 1;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
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;
|
||||
assert numberOfDigitsFaster(numbers[i]) == i + 1;
|
||||
assert numberOfDigitsRecursion(numbers[i]) == i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigits(int number) {
|
||||
int digits = 0;
|
||||
do {
|
||||
digits++;
|
||||
number /= 10;
|
||||
} while (number != 0);
|
||||
return digits;
|
||||
}
|
||||
/**
|
||||
* Find the number of digits in a number.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigits(int number) {
|
||||
int digits = 0;
|
||||
do {
|
||||
digits++;
|
||||
number /= 10;
|
||||
} while (number != 0);
|
||||
return digits;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number fast version.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigitsFast(int number) {
|
||||
return number == 0 ? 1 : (int) Math.floor(Math.log10(Math.abs(number)) + 1);
|
||||
}
|
||||
/**
|
||||
* Find the number of digits in a number fast version.
|
||||
*
|
||||
* @param number number to find
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number faster version.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigitsFaster(int number) {
|
||||
return number < 0 ? (-number + "").length() : (number + "").length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number faster version.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigitsFaster(int number) {
|
||||
return number < 0 ? (-number + "").length() : (number + "").length();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the number of digits in a number using recursion.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigitsRecursion(int number) {
|
||||
return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10);
|
||||
}
|
||||
/**
|
||||
* Find the number of digits in a number using recursion.
|
||||
*
|
||||
* @param number number to find
|
||||
* @return number of digits of given number
|
||||
*/
|
||||
private static int numberOfDigitsRecursion(int number) {
|
||||
return number / 10 == 0 ? 1 : 1 + numberOfDigitsRecursion(number / 10);
|
||||
}
|
||||
}
|
||||
|
@ -1,30 +1,30 @@
|
||||
package Maths;
|
||||
|
||||
public class PalindromeNumber {
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
assert isPalindrome(12321);
|
||||
assert !isPalindrome(1234);
|
||||
assert isPalindrome(1);
|
||||
}
|
||||
assert isPalindrome(12321);
|
||||
assert !isPalindrome(1234);
|
||||
assert isPalindrome(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code n} is palindrome number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPalindrome(int number) {
|
||||
if (number < 0) {
|
||||
throw new IllegalArgumentException(number + "");
|
||||
}
|
||||
int numberCopy = number;
|
||||
int reverseNumber = 0;
|
||||
while (numberCopy != 0) {
|
||||
int remainder = numberCopy % 10;
|
||||
reverseNumber = reverseNumber * 10 + remainder;
|
||||
numberCopy /= 10;
|
||||
}
|
||||
return number == reverseNumber;
|
||||
/**
|
||||
* Check if {@code n} is palindrome number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code n} is palindrome number, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPalindrome(int number) {
|
||||
if (number < 0) {
|
||||
throw new IllegalArgumentException(number + "");
|
||||
}
|
||||
int numberCopy = number;
|
||||
int reverseNumber = 0;
|
||||
while (numberCopy != 0) {
|
||||
int remainder = numberCopy % 10;
|
||||
reverseNumber = reverseNumber * 10 + remainder;
|
||||
numberCopy /= 10;
|
||||
}
|
||||
return number == reverseNumber;
|
||||
}
|
||||
}
|
||||
|
@ -1,33 +1,33 @@
|
||||
package Maths;
|
||||
|
||||
public class ParseInteger {
|
||||
public static void main(String[] args) {
|
||||
assert parseInt("123") == Integer.parseInt("123");
|
||||
assert parseInt("-123") == Integer.parseInt("-123");
|
||||
assert parseInt("0123") == Integer.parseInt("0123");
|
||||
assert parseInt("+123") == Integer.parseInt("+123");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert parseInt("123") == Integer.parseInt("123");
|
||||
assert parseInt("-123") == Integer.parseInt("-123");
|
||||
assert parseInt("0123") == Integer.parseInt("0123");
|
||||
assert parseInt("+123") == Integer.parseInt("+123");
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a string to integer
|
||||
*
|
||||
* @param s the string
|
||||
* @return the integer value represented by the argument in decimal.
|
||||
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
|
||||
*/
|
||||
public static int parseInt(String s) {
|
||||
if (s == null || s.length() == 0) {
|
||||
throw new NumberFormatException("null");
|
||||
}
|
||||
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) {
|
||||
if (!Character.isDigit(s.charAt(i))) {
|
||||
throw new NumberFormatException("s=" + s);
|
||||
}
|
||||
number = number * 10 + s.charAt(i) - '0';
|
||||
}
|
||||
return isNegative ? -number : number;
|
||||
/**
|
||||
* Parse a string to integer
|
||||
*
|
||||
* @param s the string
|
||||
* @return the integer value represented by the argument in decimal.
|
||||
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
|
||||
*/
|
||||
public static int parseInt(String s) {
|
||||
if (s == null || s.length() == 0) {
|
||||
throw new NumberFormatException("null");
|
||||
}
|
||||
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) {
|
||||
if (!Character.isDigit(s.charAt(i))) {
|
||||
throw new NumberFormatException("s=" + s);
|
||||
}
|
||||
number = number * 10 + s.charAt(i) - '0';
|
||||
}
|
||||
return isNegative ? -number : number;
|
||||
}
|
||||
}
|
||||
|
@ -1,27 +1,24 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* https://en.wikipedia.org/wiki/Cube_(algebra)
|
||||
*/
|
||||
/** https://en.wikipedia.org/wiki/Cube_(algebra) */
|
||||
public class PerfectCube {
|
||||
public static void main(String[] args) {
|
||||
assert !isPerfectCube(-1);
|
||||
assert isPerfectCube(0);
|
||||
assert isPerfectCube(1);
|
||||
assert !isPerfectCube(4);
|
||||
assert isPerfectCube(8);
|
||||
assert isPerfectCube(27);
|
||||
public static void main(String[] args) {
|
||||
assert !isPerfectCube(-1);
|
||||
assert isPerfectCube(0);
|
||||
assert isPerfectCube(1);
|
||||
assert !isPerfectCube(4);
|
||||
assert isPerfectCube(8);
|
||||
assert isPerfectCube(27);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is perfect cube or not
|
||||
*
|
||||
* @param number number to check
|
||||
* @return {@code true} if {@code number} is perfect cube, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPerfectCube(int number) {
|
||||
int a = (int) Math.pow(number, 1.0 / 3);
|
||||
return a * a * a == number;
|
||||
}
|
||||
/**
|
||||
* Check if a number is perfect cube or not
|
||||
*
|
||||
* @param number number to check
|
||||
* @return {@code true} if {@code number} is perfect cube, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isPerfectCube(int number) {
|
||||
int a = (int) Math.pow(number, 1.0 / 3);
|
||||
return a * a * a == number;
|
||||
}
|
||||
}
|
||||
|
@ -1,33 +1,32 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* In number theory, a perfect number is a positive integer that is equal to the sum of
|
||||
* its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3
|
||||
* (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number.
|
||||
* <p>
|
||||
* link:https://en.wikipedia.org/wiki/Perfect_number
|
||||
* </p>
|
||||
* In number theory, a perfect number is a positive integer that is equal to the sum of its positive
|
||||
* divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding
|
||||
* itself), and 1 + 2 + 3 = 6, so 6 is a perfect number.
|
||||
*
|
||||
* <p>link:https://en.wikipedia.org/wiki/Perfect_number
|
||||
*/
|
||||
public class PerfectNumber {
|
||||
public static void main(String[] args) {
|
||||
assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */
|
||||
assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */
|
||||
assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert isPerfectNumber(6); /* 1 + 2 + 3 == 6 */
|
||||
assert !isPerfectNumber(8); /* 1 + 2 + 4 != 8 */
|
||||
assert isPerfectNumber(28); /* 1 + 2 + 4 + 7 + 14 == 28 */
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if {@code number} is perfect number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code number} is perfect number, otherwise false
|
||||
*/
|
||||
public static boolean isPerfectNumber(int number) {
|
||||
int sum = 0; /* sum of its positive divisors */
|
||||
for (int i = 1; i < number; ++i) {
|
||||
if (number % i == 0) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum == number;
|
||||
/**
|
||||
* Check if {@code number} is perfect number or not
|
||||
*
|
||||
* @param number the number
|
||||
* @return {@code true} if {@code number} is perfect number, otherwise false
|
||||
*/
|
||||
public static boolean isPerfectNumber(int number) {
|
||||
int sum = 0; /* sum of its positive divisors */
|
||||
for (int i = 1; i < number; ++i) {
|
||||
if (number % i == 0) {
|
||||
sum += i;
|
||||
}
|
||||
}
|
||||
return sum == number;
|
||||
}
|
||||
}
|
||||
|
@ -1,25 +1,23 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* https://en.wikipedia.org/wiki/Perfect_square
|
||||
*/
|
||||
/** https://en.wikipedia.org/wiki/Perfect_square */
|
||||
public class PerfectSquare {
|
||||
public static void main(String[] args) {
|
||||
assert !isPerfectSquare(-1);
|
||||
assert !isPerfectSquare(3);
|
||||
assert !isPerfectSquare(5);
|
||||
assert isPerfectSquare(9);
|
||||
assert isPerfectSquare(100);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert !isPerfectSquare(-1);
|
||||
assert !isPerfectSquare(3);
|
||||
assert !isPerfectSquare(5);
|
||||
assert isPerfectSquare(9);
|
||||
assert isPerfectSquare(100);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a number is perfect square number
|
||||
*
|
||||
* @param number the number to be checked
|
||||
* @return <tt>true</tt> if {@code number} is perfect square, otherwise <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPerfectSquare(int number) {
|
||||
int sqrt = (int) Math.sqrt(number);
|
||||
return sqrt * sqrt == number;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Check if a number is perfect square number
|
||||
*
|
||||
* @param number the number to be checked
|
||||
* @return <tt>true</tt> if {@code number} is perfect square, otherwise <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPerfectSquare(int number) {
|
||||
int sqrt = (int) Math.sqrt(number);
|
||||
return sqrt * sqrt == number;
|
||||
}
|
||||
}
|
||||
|
@ -1,27 +1,26 @@
|
||||
package Maths;
|
||||
|
||||
//POWER (exponentials) Examples (a^b)
|
||||
// POWER (exponentials) Examples (a^b)
|
||||
public class Pow {
|
||||
public static void main(String[] args) {
|
||||
assert pow(2, 0) == Math.pow(2, 0); // == 1
|
||||
assert pow(0, 2) == Math.pow(0, 2); // == 0
|
||||
assert pow(2, 10) == Math.pow(2, 10); // == 1024
|
||||
assert pow(10, 2) == Math.pow(10, 2); // == 100
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert pow(2, 0) == Math.pow(2, 0); // == 1
|
||||
assert pow(0, 2) == Math.pow(0, 2); // == 0
|
||||
assert pow(2, 10) == Math.pow(2, 10); // == 1024
|
||||
assert pow(10, 2) == Math.pow(10, 2); // == 100
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the
|
||||
* second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
long result = 1;
|
||||
for (int i = 1; i <= b; i++) {
|
||||
result *= a;
|
||||
}
|
||||
return result;
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
long result = 1;
|
||||
for (int i = 1; i <= b; i++) {
|
||||
result *= a;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
@ -1,22 +1,21 @@
|
||||
package Maths;
|
||||
|
||||
public class PowRecursion {
|
||||
public static void main(String[] args) {
|
||||
assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0;
|
||||
assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0;
|
||||
assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0;
|
||||
assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert Double.compare(pow(2, 0), Math.pow(2, 0)) == 0;
|
||||
assert Double.compare(pow(0, 2), Math.pow(0, 2)) == 0;
|
||||
assert Double.compare(pow(2, 10), Math.pow(2, 10)) == 0;
|
||||
assert Double.compare(pow(10, 2), Math.pow(10, 2)) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the
|
||||
* second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
return b == 0 ? 1 : a * pow(a, b - 1);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns the value of the first argument raised to the power of the second argument
|
||||
*
|
||||
* @param a the base.
|
||||
* @param b the exponent.
|
||||
* @return the value {@code a}<sup>{@code b}</sup>.
|
||||
*/
|
||||
public static long pow(int a, int b) {
|
||||
return b == 0 ? 1 : a * pow(a, b - 1);
|
||||
}
|
||||
}
|
||||
|
@ -1,28 +1,23 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* A utility to check if a given number is power of two or not.
|
||||
* For example 8,16 etc.
|
||||
*/
|
||||
|
||||
/** A utility to check if a given number is power of two or not. For example 8,16 etc. */
|
||||
public class PowerOfTwoOrNot {
|
||||
|
||||
public static void main(String[] args) {
|
||||
assert !checkIfPowerOfTwoOrNot(0);
|
||||
assert checkIfPowerOfTwoOrNot(1);
|
||||
assert checkIfPowerOfTwoOrNot(8);
|
||||
assert checkIfPowerOfTwoOrNot(16);
|
||||
assert checkIfPowerOfTwoOrNot(1024);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert !checkIfPowerOfTwoOrNot(0);
|
||||
assert checkIfPowerOfTwoOrNot(1);
|
||||
assert checkIfPowerOfTwoOrNot(8);
|
||||
assert checkIfPowerOfTwoOrNot(16);
|
||||
assert checkIfPowerOfTwoOrNot(1024);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Checks whether given number is power of two or not.
|
||||
*
|
||||
* @param number the number to check
|
||||
* @return {@code true} if given number is power of two, otherwise {@code false}
|
||||
*/
|
||||
public static boolean checkIfPowerOfTwoOrNot(int number) {
|
||||
return number != 0 && ((number & (number - 1)) == 0);
|
||||
}
|
||||
/**
|
||||
* Checks whether given number is power of two or not.
|
||||
*
|
||||
* @param number the number to check
|
||||
* @return {@code true} if given number is power of two, otherwise {@code false}
|
||||
*/
|
||||
public static boolean checkIfPowerOfTwoOrNot(int number) {
|
||||
return number != 0 && ((number & (number - 1)) == 0);
|
||||
}
|
||||
}
|
||||
|
@ -3,36 +3,36 @@ package Maths;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class PrimeCheck {
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
public static void main(String[] args) {
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
System.out.print("Enter a number: ");
|
||||
int n = scanner.nextInt();
|
||||
if (isPrime(n)) {
|
||||
System.out.println(n + " is a prime number");
|
||||
} else {
|
||||
System.out.println(n + " is not a prime number");
|
||||
}
|
||||
scanner.close();
|
||||
System.out.print("Enter a number: ");
|
||||
int n = scanner.nextInt();
|
||||
if (isPrime(n)) {
|
||||
System.out.println(n + " is a prime number");
|
||||
} else {
|
||||
System.out.println(n + " is not a prime number");
|
||||
}
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
/***
|
||||
* Checks if a number is prime or not
|
||||
* @param n the number
|
||||
* @return {@code true} if {@code n} is prime
|
||||
*/
|
||||
public static boolean isPrime(int n) {
|
||||
if (n == 2) {
|
||||
return true;
|
||||
}
|
||||
if (n < 2 || n % 2 == 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
/***
|
||||
* Checks if a number is prime or not
|
||||
* @param n the number
|
||||
* @return {@code true} if {@code n} is prime
|
||||
*/
|
||||
public static boolean isPrime(int n) {
|
||||
if (n == 2) {
|
||||
return true;
|
||||
}
|
||||
if (n < 2 || n % 2 == 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 3, limit = (int) Math.sqrt(n); i <= limit; i += 2) {
|
||||
if (n % i == 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -1,36 +1,32 @@
|
||||
package Maths;
|
||||
|
||||
import java.lang.Math;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class PrimeFactorization {
|
||||
public static void main(String[] args){
|
||||
System.out.println("## all prime factors ##");
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter a number: ");
|
||||
int n = scanner.nextInt();
|
||||
System.out.print(("printing factors of " + n + " : "));
|
||||
pfactors(n);
|
||||
scanner.close();
|
||||
public static void main(String[] args) {
|
||||
System.out.println("## all prime factors ##");
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
System.out.print("Enter a number: ");
|
||||
int n = scanner.nextInt();
|
||||
System.out.print(("printing factors of " + n + " : "));
|
||||
pfactors(n);
|
||||
scanner.close();
|
||||
}
|
||||
|
||||
public static void pfactors(int n) {
|
||||
|
||||
while (n % 2 == 0) {
|
||||
System.out.print(2 + " ");
|
||||
n /= 2;
|
||||
}
|
||||
public static void pfactors(int n){
|
||||
|
||||
while (n%2==0)
|
||||
{
|
||||
System.out.print(2 + " ");
|
||||
n /= 2;
|
||||
}
|
||||
|
||||
for (int i=3; i<= Math.sqrt(n); i+=2)
|
||||
{
|
||||
while (n%i == 0)
|
||||
{
|
||||
System.out.print(i + " ");
|
||||
n /= i;
|
||||
}
|
||||
}
|
||||
|
||||
if(n > 2)
|
||||
System.out.print(n);
|
||||
for (int i = 3; i <= Math.sqrt(n); i += 2) {
|
||||
while (n % i == 0) {
|
||||
System.out.print(i + " ");
|
||||
n /= i;
|
||||
}
|
||||
}
|
||||
|
||||
if (n > 2) System.out.print(n);
|
||||
}
|
||||
}
|
||||
|
@ -1,32 +1,30 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* https://en.wikipedia.org/wiki/Pythagorean_triple
|
||||
*
|
||||
*/
|
||||
/** https://en.wikipedia.org/wiki/Pythagorean_triple */
|
||||
public class PythagoreanTriple {
|
||||
public static void main(String[] args) {
|
||||
assert isPythagTriple(3,4,5);
|
||||
assert isPythagTriple(5,12,13);
|
||||
assert isPythagTriple(6,8,10);
|
||||
assert !isPythagTriple(10,20,30);
|
||||
assert !isPythagTriple(6,8,100);
|
||||
assert !isPythagTriple(-1,-1,1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a,b,c are a Pythagorean Triple
|
||||
*
|
||||
* @param a x/y component length of a right triangle
|
||||
* @param b y/x component length of a right triangle
|
||||
* @param c hypotenuse length of a right triangle
|
||||
* @return boolean <tt>true</tt> if a, b, c satisfy the Pythagorean theorem, otherwise <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPythagTriple(int a, int b, int c) {
|
||||
if(a <= 0 || b <= 0 || c <= 0) {
|
||||
return false;
|
||||
} else {
|
||||
return (a * a) + (b * b) == (c * c);
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
assert isPythagTriple(3, 4, 5);
|
||||
assert isPythagTriple(5, 12, 13);
|
||||
assert isPythagTriple(6, 8, 10);
|
||||
assert !isPythagTriple(10, 20, 30);
|
||||
assert !isPythagTriple(6, 8, 100);
|
||||
assert !isPythagTriple(-1, -1, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a,b,c are a Pythagorean Triple
|
||||
*
|
||||
* @param a x/y component length of a right triangle
|
||||
* @param b y/x component length of a right triangle
|
||||
* @param c hypotenuse length of a right triangle
|
||||
* @return boolean <tt>true</tt> if a, b, c satisfy the Pythagorean theorem, otherwise
|
||||
* <tt>false</tt>
|
||||
*/
|
||||
public static boolean isPythagTriple(int a, int b, int c) {
|
||||
if (a <= 0 || b <= 0 || c <= 0) {
|
||||
return false;
|
||||
} else {
|
||||
return (a * a) + (b * b) == (c * c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,40 +1,40 @@
|
||||
package Maths;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers such that the
|
||||
* difference between the consecutive terms is constant. Difference here means the second minus the first.
|
||||
* For instance, the sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common difference of 2.
|
||||
* <p>
|
||||
* Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression
|
||||
* In mathematics, an arithmetic progression (AP) or arithmetic sequence is a sequence of numbers
|
||||
* such that the difference between the consecutive terms is constant. Difference here means the
|
||||
* second minus the first. For instance, the sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic
|
||||
* progression with common difference of 2.
|
||||
*
|
||||
* <p>Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression
|
||||
*/
|
||||
public class SumOfArithmeticSeries {
|
||||
public static void main(String[] args) {
|
||||
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;
|
||||
/* 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 */
|
||||
assert Double.compare(55.0, sumOfSeries(1, 1, 10)) == 0;
|
||||
|
||||
/* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */
|
||||
assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0;
|
||||
/* 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 */
|
||||
assert Double.compare(100.0, sumOfSeries(1, 2, 10)) == 0;
|
||||
|
||||
/* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */
|
||||
assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0;
|
||||
/* 1 + 11 + 21 + 31 + 41 + 51 + 61 + 71 + 81 + 91 */
|
||||
assert Double.compare(460.0, sumOfSeries(1, 10, 10)) == 0;
|
||||
|
||||
/* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */
|
||||
assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0;
|
||||
/* 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 0.6 + 0.7 + 0.8 + 0.9 + 1.0 */
|
||||
assert Double.compare(5.5, sumOfSeries(0.1, 0.1, 10)) == 0;
|
||||
|
||||
assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0;
|
||||
}
|
||||
assert Double.compare(49600.0, sumOfSeries(1, 10, 100)) == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate sum of arithmetic series
|
||||
*
|
||||
* @param firstTerm the initial term of an arithmetic series
|
||||
* @param commonDiff the common difference of an arithmetic series
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Calculate sum of arithmetic series
|
||||
*
|
||||
* @param firstTerm the initial term of an arithmetic series
|
||||
* @param commonDiff the common difference of an arithmetic series
|
||||
* @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);
|
||||
}
|
||||
}
|
||||
|
@ -1,62 +1,56 @@
|
||||
package Maths;
|
||||
|
||||
public class SumOfDigits {
|
||||
public static void main(String[] args) {
|
||||
assert
|
||||
sumOfDigits(-123) == 6
|
||||
&& sumOfDigitsRecursion(-123) == 6
|
||||
&& sumOfDigitsFast(-123) == 6;
|
||||
public static void main(String[] args) {
|
||||
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;
|
||||
/**
|
||||
* Calculate the sum of digits of a number
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigits(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
int sum = 0;
|
||||
while (number != 0) {
|
||||
sum += number % 10;
|
||||
number /= 10;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the sum of digits of a number
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigits(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
int sum = 0;
|
||||
while (number != 0) {
|
||||
sum += number % 10;
|
||||
number /= 10;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
/**
|
||||
* Calculate the sum of digits of a number using recursion
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigitsRecursion(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the sum of digits of a number using recursion
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigitsRecursion(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
return number < 10 ? number : number % 10 + sumOfDigitsRecursion(number / 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the sum of digits of a number using char array
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigitsFast(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
char[] digits = (number + "").toCharArray();
|
||||
int sum = 0;
|
||||
for (int i = 0; i < digits.length; ++i) {
|
||||
sum += digits[i] - '0';
|
||||
}
|
||||
return sum;
|
||||
/**
|
||||
* Calculate the sum of digits of a number using char array
|
||||
*
|
||||
* @param number the number contains digits
|
||||
* @return sum of digits of given {@code number}
|
||||
*/
|
||||
public static int sumOfDigitsFast(int number) {
|
||||
number = number < 0 ? -number : number; /* calculate abs value */
|
||||
char[] digits = (number + "").toCharArray();
|
||||
int sum = 0;
|
||||
for (int i = 0; i < digits.length; ++i) {
|
||||
sum += digits[i] - '0';
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
|
@ -2,93 +2,77 @@ package Maths;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
n number theory, a vampire number (or true vampire number) is a composite natural number with an even number of digits,
|
||||
that can be factored into two natural numbers each with half as many digits as the original number
|
||||
and not both with trailing zeroes, where the two factors contain precisely
|
||||
all the digits of the original number, in any order, counting multiplicity.
|
||||
The first vampire number is 1260 = 21 × 60.
|
||||
* *
|
||||
* <p>
|
||||
* * link: https://en.wikipedia.org/wiki/Vampire_number
|
||||
* * </p>
|
||||
* <p>
|
||||
* n number theory, a vampire number (or true vampire number) is a composite natural number with an
|
||||
* even number of digits, that can be factored into two natural numbers each with half as many
|
||||
* digits as the original number and not both with trailing zeroes, where the two factors contain
|
||||
* precisely all the digits of the original number, in any order, counting multiplicity. The first
|
||||
* vampire number is 1260 = 21 × 60. *
|
||||
*
|
||||
* <p>* link: https://en.wikipedia.org/wiki/Vampire_number *
|
||||
*
|
||||
* <p>
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
public class VampireNumber {
|
||||
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) {
|
||||
|
||||
test(10,1000);
|
||||
test(10, 1000);
|
||||
}
|
||||
|
||||
static void test(int startValue, int stopValue) {
|
||||
int countofRes = 1;
|
||||
StringBuilder res = new StringBuilder();
|
||||
|
||||
for (int i = startValue; i <= stopValue; i++) {
|
||||
for (int j = i; j <= stopValue; j++) {
|
||||
// System.out.println(i+ " "+ j);
|
||||
if (isVampireNumber(i, j, true)) {
|
||||
countofRes++;
|
||||
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
|
||||
if (noPseudoVamireNumbers) {
|
||||
if (a * 10 <= b || b * 10 <= a) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static void test(int startValue, int stopValue) {
|
||||
int countofRes = 1;
|
||||
StringBuilder res = new StringBuilder();
|
||||
String mulDigits = splitIntoDigits(a * b, 0);
|
||||
String faktorDigits = splitIntoDigits(a, b);
|
||||
|
||||
return mulDigits.equals(faktorDigits);
|
||||
}
|
||||
|
||||
for (int i = startValue; i <= stopValue; i++) {
|
||||
for (int j = i; j <= stopValue; j++) {
|
||||
// System.out.println(i+ " "+ j);
|
||||
if (isVampireNumber(i, j,true)) {
|
||||
countofRes++;
|
||||
res.append("" + countofRes + ": = ( " + i + "," + j + " = " + i*j + ")" + "\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println(res);
|
||||
}
|
||||
// methode to Split the numbers to Digits
|
||||
static String splitIntoDigits(int num, int num2) {
|
||||
|
||||
StringBuilder res = new StringBuilder();
|
||||
|
||||
ArrayList<Integer> digits = new ArrayList<>();
|
||||
while (num > 0) {
|
||||
digits.add(num % 10);
|
||||
num /= 10;
|
||||
}
|
||||
while (num2 > 0) {
|
||||
digits.add(num2 % 10);
|
||||
num2 /= 10;
|
||||
}
|
||||
Collections.sort(digits);
|
||||
for (int i : digits) {
|
||||
res.append(i);
|
||||
}
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
String mulDigits = splitIntoDigits(a*b,0);
|
||||
String faktorDigits = splitIntoDigits(a,b);
|
||||
|
||||
return mulDigits.equals(faktorDigits);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// methode to Split the numbers to Digits
|
||||
static String splitIntoDigits(int num, int num2) {
|
||||
|
||||
StringBuilder res = new StringBuilder();
|
||||
|
||||
ArrayList<Integer> digits = new ArrayList<>();
|
||||
while (num > 0) {
|
||||
digits.add(num%10);
|
||||
num /= 10;
|
||||
}
|
||||
while (num2 > 0) {
|
||||
digits.add(num2%10);
|
||||
num2/= 10;
|
||||
}
|
||||
Collections.sort(digits);
|
||||
for (int i : digits) {
|
||||
res.append(i);
|
||||
}
|
||||
|
||||
|
||||
return res.toString();
|
||||
}
|
||||
return res.toString();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user