Add another method to check Pronic number (#5919)

This commit is contained in:
Taranjeet Singh Kalsi
2024-10-26 16:49:16 +05:30
committed by GitHub
parent 1577ec4e62
commit 871e4df0d9
2 changed files with 27 additions and 24 deletions

View File

@@ -21,6 +21,9 @@ public final class PronicNumber {
* @return true if input number is a pronic number, false otherwise
*/
static boolean isPronic(int inputNumber) {
if (inputNumber == 0) {
return true;
}
// Iterating from 0 to input_number
for (int i = 0; i <= inputNumber; i++) {
// Checking if product of i and (i+1) is equals input_number
@@ -34,4 +37,15 @@ public final class PronicNumber {
// equals input_number
return false;
}
/**
* This method checks if the given number is pronic number or non-pronic number using square root of number for finding divisors
*
* @param number Integer value which is to be checked if is a pronic number or not
* @return true if input number is a pronic number, false otherwise
*/
public static boolean isPronicNumber(int number) {
int squareRoot = (int) Math.sqrt(number); // finding just smaller divisor of the number than its square root.
return squareRoot * (squareRoot + 1) == number;
}
}

View File

@@ -1,33 +1,22 @@
package com.thealgorithms.maths;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class PronicNumberTest {
@Test
void testForPronicNumber() {
// given
int number = 30;
// when
boolean result = PronicNumber.isPronic(number);
// then
assertTrue(result);
@ParameterizedTest
@ValueSource(ints = {0, 2, 6, 12, 20, 30, 42, 110, 272, 380, 420, 1260, 2550})
void testForPronicNumber(final int number) {
Assertions.assertTrue(PronicNumber.isPronic(number));
Assertions.assertTrue(PronicNumber.isPronicNumber(number));
}
@Test
void testForNonPronicNumber() {
// given
int number = 21;
// when
boolean result = PronicNumber.isPronic(number);
// then
assertFalse(result);
@ParameterizedTest
@ValueSource(ints = {1, 4, 21, 36, 150, 2500})
void testForNonPronicNumber(final int number) {
Assertions.assertFalse(PronicNumber.isPronic(number));
Assertions.assertFalse(PronicNumber.isPronicNumber(number));
}
}