Merge branch 'master' of https://github.com/eugenp/tutorials into BAEL-16045-3

This commit is contained in:
amit2103
2019-10-27 19:39:47 +05:30
4564 changed files with 284202 additions and 23978 deletions

View File

@@ -1,14 +1,10 @@
=========
## Java Number Cookbooks and Examples
This module contains articles about numbers in Java.
### Relevant Articles:
- [Number of Digits in an Integer in Java](http://www.baeldung.com/java-number-of-digits-in-int)
- [NaN in Java](http://www.baeldung.com/java-not-a-number)
- [How to Round a Number to N Decimal Places in Java](http://www.baeldung.com/java-round-decimal-number)
- [Check If a Number Is Prime in Java](http://www.baeldung.com/java-prime-numbers)
- [Using Math.pow in Java](http://www.baeldung.com/java-math-pow)
- [Generating Prime Numbers in Java](http://www.baeldung.com/java-generate-prime-numbers)
- [BigDecimal and BigInteger in Java](http://www.baeldung.com/java-bigdecimal-biginteger)
- [Find All Pairs of Numbers in an Array That Add Up to a Given Sum](http://www.baeldung.com/java-algorithm-number-pairs-sum)
- [Java Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double)
@@ -17,5 +13,4 @@
- [Calculating the nth Root in Java](https://www.baeldung.com/java-nth-root)
- [Convert Double to String, Removing Decimal Places](https://www.baeldung.com/java-double-to-string)
- [Changing the Order in a Sum Operation Can Produce Different Results?](https://www.baeldung.com/java-floating-point-sum-order)
- [Calculate the Area of a Circle in Java](https://www.baeldung.com/java-calculate-circle-area)
- [A Guide to the Java Math Class](https://www.baeldung.com/java-lang-math)
- More articles: [[next -->]](/../java-numbers-2)

View File

@@ -1,13 +0,0 @@
package com.baeldung.algorithms.primechecker;
import java.math.BigInteger;
public class BigIntegerPrimeChecker implements PrimeChecker<Long>{
@Override
public boolean isPrime(Long number) {
BigInteger bigInt = BigInteger.valueOf(number);
return bigInt.isProbablePrime(100);
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class BruteForcePrimeChecker implements PrimeChecker<Integer> {
@Override
public boolean isPrime(Integer number) {
return number > 2 ? IntStream.range(2, number)
.noneMatch(n -> (number % n == 0)) : false;
}
}

View File

@@ -1,13 +0,0 @@
package com.baeldung.algorithms.primechecker;
import java.util.stream.IntStream;
public class OptimisedPrimeChecker implements PrimeChecker<Integer> {
@Override
public boolean isPrime(Integer number) {
return number > 2 ? IntStream.rangeClosed(2, (int) Math.sqrt(number))
.noneMatch(n -> (number % n == 0)) : false;
}
}

View File

@@ -1,6 +0,0 @@
package com.baeldung.algorithms.primechecker;
public interface PrimeChecker <T> {
public boolean isPrime( T number );
}

View File

@@ -1,12 +0,0 @@
package com.baeldung.algorithms.primechecker;
import org.apache.commons.math3.primes.Primes;
public class PrimesPrimeChecker implements PrimeChecker<Integer>{
@Override
public boolean isPrime(Integer number) {
return Primes.isPrime(number);
}
}

View File

@@ -1,26 +0,0 @@
package com.baeldung.area.circle;
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
private double calculateArea() {
return radius * radius * Math.PI;
}
public String toString() {
return "The area of the circle [radius = " + radius + "]: " + calculateArea();
}
}

View File

@@ -1,36 +0,0 @@
package com.baeldung.area.circle;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
if (args.length > 0) {
try {
double radius = Double.parseDouble(args[0]);
calculateArea(radius);
} catch (NumberFormatException nfe) {
System.out.println("Invalid value for radius");
System.exit(0);
}
}
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Please enter radius value: ");
double radius = scanner.nextDouble();
calculateArea(radius);
} catch (InputMismatchException e) {
System.out.println("Invalid value for radius");
System.exit(0);
}
Circle circle = new Circle(7);
System.out.println(circle);
}
private static void calculateArea(double radius) {
double area = radius * radius * Math.PI;
System.out.println("The area of the circle [radius = " + radius + "]: " + area);
}
}

View File

@@ -1,81 +0,0 @@
package com.baeldung.nan;
/**
* Sample usage of NaN.
*
*/
public class NaNExample {
public static void main(String[] args) {
NaNExample naNExample = new NaNExample();
naNExample.demo();
}
void demo() {
undefined_operations_produce_NaN();
operations_with_no_real_results_produce_NaN();
operations_with_NaN_produce_NaN();
comparison_with_NaN();
check_if_a_value_is_NaN();
assign_NaN_to_missing_values();
}
void undefined_operations_produce_NaN() {
System.out.println("Undefined Operations Produce NaN");
final double ZERO = 0;
System.out.println("ZERO / ZERO = " + (ZERO / ZERO));
System.out.println("INFINITY - INFINITY = " + (Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY));
System.out.println("INFINITY * ZERO = " + (Double.POSITIVE_INFINITY * ZERO));
System.out.println();
}
void operations_with_no_real_results_produce_NaN() {
System.out.println("Operations with no real results produce NaN");
System.out.println("SQUARE ROOT OF -1 = " + Math.sqrt(-1));
System.out.println("LOG OF -1 = " + Math.log(-1));
System.out.println();
}
void operations_with_NaN_produce_NaN() {
System.out.println("Operations with NaN produce NaN");
System.out.println("2 + NaN = " + (2 + Double.NaN));
System.out.println("2 - NaN = " + (2 - Double.NaN));
System.out.println("2 * NaN = " + (2 * Double.NaN));
System.out.println("2 / NaN = " + (2 / Double.NaN));
System.out.println();
}
void assign_NaN_to_missing_values() {
System.out.println("Assign NaN to Missing values");
double salaryRequired = Double.NaN;
System.out.println(salaryRequired);
System.out.println();
}
void comparison_with_NaN() {
System.out.println("Comparison with NaN");
final double NAN = Double.NaN;
System.out.println("NaN == 1 = " + (NAN == 1));
System.out.println("NaN > 1 = " + (NAN > 1));
System.out.println("NaN < 1 = " + (NAN < 1));
System.out.println("NaN != 1 = " + (NAN != 1));
System.out.println("NaN == NaN = " + (NAN == NAN));
System.out.println("NaN > NaN = " + (NAN > NAN));
System.out.println("NaN < NaN = " + (NAN < NAN));
System.out.println("NaN != NaN = " + (NAN != NAN));
System.out.println();
}
void check_if_a_value_is_NaN() {
System.out.println("Check if a value is NaN");
double x = 1;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
x = Double.NaN;
System.out.println(x + " is NaN = " + (x != x));
System.out.println(x + " is NaN = " + (Double.isNaN(x)));
System.out.println();
}
}

View File

@@ -1,8 +1,12 @@
package com.baeldung.nth.root.calculator;
public class NthRootCalculator
{
public Double calculate(Double base, Double n) {
return Math.pow(Math.E, Math.log(base)/n);
public class NthRootCalculator {
public double calculateWithRound(double base, double n) {
return Math.round(calculate(base, n));
}
public double calculate(double base, double n) {
return Math.pow(base, 1.0 / n);
}
}

View File

@@ -7,7 +7,7 @@ public class Main {
NthRootCalculator calculator = new NthRootCalculator();
Double base = Double.parseDouble(args[0]);
Double n = Double.parseDouble(args[1]);
Double result = calculator.calculate(base, n);
Double result = calculator.calculateWithRound(base, n);
System.out.println("The " + n + " root of " + base + " equals to " + result + ".");
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.pow;
import java.text.DecimalFormat;
public class PowerExample {
public static void main(String[] args) {
int intResult = (int) Math.pow(2, 3);
System.out.println("Math.pow(2, 3) = " + intResult);
double dblResult = Math.pow(4.2, 3);
System.out.println("Math.pow(4.2, 3) = " + Math.pow(4.2, 3));
DecimalFormat df = new DecimalFormat(".00");
System.out.println("Math.pow(4.2, 3) rounded = " + df.format(dblResult));
}
}

View File

@@ -1,59 +0,0 @@
package com.baeldung.prime;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PrimeGenerator {
public static List<Integer> sieveOfEratosthenes(int n) {
final boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
final List<Integer> primes = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i])
primes.add(i);
}
return primes;
}
public static List<Integer> primeNumbersBruteForce(int max) {
final List<Integer> primeNumbers = new LinkedList<Integer>();
for (int i = 2; i <= max; i++) {
if (isPrimeBruteForce(i)) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
private static boolean isPrimeBruteForce(int x) {
for (int i = 2; i < x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
public static List<Integer> primeNumbersTill(int max) {
return IntStream.rangeClosed(2, max)
.filter(x -> isPrime(x))
.boxed()
.collect(Collectors.toList());
}
private static boolean isPrime(int x) {
return IntStream.rangeClosed(2, (int) (Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
}

View File

@@ -1,68 +0,0 @@
package com.baeldung.algorithms.primechecker;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class PrimeCheckerUnitTest {
private final BigIntegerPrimeChecker primeChecker = new BigIntegerPrimeChecker();
@Test
public void whenCheckIsPrime_thenTrue() {
assertTrue(primeChecker.isPrime(13l));
assertTrue(primeChecker.isPrime(1009L));
assertTrue(primeChecker.isPrime(74207281L));
}
@Test
public void whenCheckIsPrime_thenFalse() {
assertTrue(!primeChecker.isPrime(50L));
assertTrue(!primeChecker.isPrime(1001L));
assertTrue(!primeChecker.isPrime(74207282L));
}
private final BruteForcePrimeChecker bfPrimeChecker = new BruteForcePrimeChecker();
@Test
public void whenBFCheckIsPrime_thenTrue() {
assertTrue(bfPrimeChecker.isPrime(13));
assertTrue(bfPrimeChecker.isPrime(1009));
}
@Test
public void whenBFCheckIsPrime_thenFalse() {
assertFalse(bfPrimeChecker.isPrime(50));
assertFalse(bfPrimeChecker.isPrime(1001));
}
private final OptimisedPrimeChecker optimisedPrimeChecker = new OptimisedPrimeChecker();
@Test
public void whenOptCheckIsPrime_thenTrue() {
assertTrue(optimisedPrimeChecker.isPrime(13));
assertTrue(optimisedPrimeChecker.isPrime(1009));
}
@Test
public void whenOptCheckIsPrime_thenFalse() {
assertFalse(optimisedPrimeChecker.isPrime(50));
assertFalse(optimisedPrimeChecker.isPrime(1001));
}
private final PrimesPrimeChecker primesPrimeChecker = new PrimesPrimeChecker();
@Test
public void whenPrimesCheckIsPrime_thenTrue() {
assertTrue(primesPrimeChecker.isPrime(13));
assertTrue(primesPrimeChecker.isPrime(1009));
}
@Test
public void whenPrimesCheckIsPrime_thenFalse() {
assertFalse(primesPrimeChecker.isPrime(50));
assertFalse(primesPrimeChecker.isPrime(1001));
}
}

View File

@@ -1,175 +0,0 @@
package com.baeldung.java.math;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MathUnitTest {
@Test
public void whenAbsInteger_thenReturnAbsoluteValue() {
assertEquals(5,Math.abs(-5));
}
@Test
public void whenMaxBetweenTwoValue_thenReturnMaximum() {
assertEquals(10, Math.max(5,10));
}
@Test
public void whenMinBetweenTwoValue_thenReturnMinimum() {
assertEquals(5, Math.min(5,10));
}
@Test
public void whenSignumWithNegativeNumber_thenReturnMinusOne() {
assertEquals(-1, Math.signum(-5), 0);
}
@Test
public void whenCopySignWithNegativeSign_thenReturnNegativeArgument() {
assertEquals(-5, Math.copySign(5,-1), 0);
}
@Test
public void whenPow_thenReturnPoweredValue() {
assertEquals(25, Math.pow(5,2),0);
}
@Test
public void whenSqrt_thenReturnSquareRoot() {
assertEquals(5, Math.sqrt(25),0);
}
@Test
public void whenCbrt_thenReturnCubeRoot() {
assertEquals(5, Math.cbrt(125),0);
}
@Test
public void whenExp_thenReturnEulerNumberRaised() {
assertEquals(2.718, Math.exp(1),0.1);
}
@Test
public void whenExpm1_thenReturnEulerNumberMinusOne() {
assertEquals(1.718, Math.expm1(1),0.1);
}
@Test
public void whenGetExponent_thenReturnUnbiasedExponent() {
assertEquals(8, Math.getExponent(333.3),0);
assertEquals(7, Math.getExponent(222.2f),0);
}
@Test
public void whenLog_thenReturnValue() {
assertEquals(1, Math.log(Math.E),0);
}
@Test
public void whenLog10_thenReturnValue() {
assertEquals(1, Math.log10(10),0);
}
@Test
public void whenLog1p_thenReturnValue() {
assertEquals(1.31, Math.log1p(Math.E),0.1);
}
@Test
public void whenSin_thenReturnValue() {
assertEquals(1, Math.sin(Math.PI/2),0);
}
@Test
public void whenCos_thenReturnValue() {
assertEquals(1, Math.cos(0),0);
}
@Test
public void whenTan_thenReturnValue() {
assertEquals(1, Math.tan(Math.PI/4),0.1);
}
@Test
public void whenAsin_thenReturnValue() {
assertEquals(Math.PI/2, Math.asin(1),0);
}
@Test
public void whenAcos_thenReturnValue() {
assertEquals(Math.PI/2, Math.acos(0),0);
}
@Test
public void whenAtan_thenReturnValue() {
assertEquals(Math.PI/4, Math.atan(1),0);
}
@Test
public void whenAtan2_thenReturnValue() {
assertEquals(Math.PI/4, Math.atan2(1,1),0);
}
@Test
public void whenToDegrees_thenReturnValue() {
assertEquals(180, Math.toDegrees(Math.PI),0);
}
@Test
public void whenToRadians_thenReturnValue() {
assertEquals(Math.PI, Math.toRadians(180),0);
}
@Test
public void whenCeil_thenReturnValue() {
assertEquals(4, Math.ceil(Math.PI),0);
}
@Test
public void whenFloor_thenReturnValue() {
assertEquals(3, Math.floor(Math.PI),0);
}
@Test
public void whenGetExponent_thenReturnValue() {
assertEquals(8, Math.getExponent(333.3),0);
}
@Test
public void whenIEEERemainder_thenReturnValue() {
assertEquals(1.0, Math.IEEEremainder(5,2),0);
}
@Test
public void whenNextAfter_thenReturnValue() {
assertEquals(1.9499999284744263, Math.nextAfter(1.95f,1),0.0000001);
}
@Test
public void whenNextUp_thenReturnValue() {
assertEquals(1.9500002, Math.nextUp(1.95f),0.0000001);
}
@Test
public void whenRint_thenReturnValue() {
assertEquals(2.0, Math.rint(1.95f),0.0);
}
@Test
public void whenRound_thenReturnValue() {
assertEquals(2.0, Math.round(1.95f),0.0);
}
@Test
public void whenScalb_thenReturnValue() {
assertEquals(48, Math.scalb(3, 4),0.0);
}
@Test
public void whenHypot_thenReturnValue() {
assertEquals(5, Math.hypot(4, 3),0.0);
}
}

View File

@@ -1,19 +1,22 @@
package com.baeldung.nth.root.calculator;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
public class NthRootCalculatorUnitTest {
private NthRootCalculator nthRootCalculator = new NthRootCalculator();
@Test
public void whenBaseIs125AndNIs3_thenNthRootIs5() {
Double result = nthRootCalculator.calculate(125.0, 3.0);
assertEquals(result, (Double) 5.0d);
public void whenBaseIs125AndNIs3_thenNthIs5() {
double nth = nthRootCalculator.calculateWithRound(125,3);
assertEquals(5, nth, 0);
}
@Test
public void whenBaseIs625AndNIs4_thenNthIs5() {
double nth = nthRootCalculator.calculate(625,4);
assertEquals(5, nth, 0.00001);
}
}

View File

@@ -1,34 +0,0 @@
package com.baeldung.nth.root.main;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import static org.junit.Assert.assertEquals;
public class MainUnitTest {
@InjectMocks
private Main main;
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
public void givenThatTheBaseIs125_andTheExpIs3_whenMainIsCalled_thenTheCorrectResultIsPrinted() {
main.main(new String[]{"125.0", "3.0"});
assertEquals("The 3.0 root of 125.0 equals to 5.0.\n", outContent.toString().replaceAll("\r", ""));
}
}

View File

@@ -1,28 +0,0 @@
package com.baeldung.prime;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import static com.baeldung.prime.PrimeGenerator.*;
import static org.junit.Assert.*;
public class PrimeGeneratorUnitTest {
@Test
public void whenBruteForced_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersBruteForce(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenOptimized_returnsSuccessfully() {
final List<Integer> primeNumbers = primeNumbersTill(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
@Test
public void whenSieveOfEratosthenes_returnsSuccessfully() {
final List<Integer> primeNumbers = sieveOfEratosthenes(20);
assertEquals(Arrays.asList(new Integer[] { 2, 3, 5, 7, 11, 13, 17, 19 }), primeNumbers);
}
}