Skip to content

Commit 0c85933

Browse files
Add SquareFreeInteger to maths
1 parent a508fd2 commit 0c85933

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public final class SquareFreeInteger{
2+
3+
/**
4+
* A square-free integer is an integer divisible by no perfect square other than 1
5+
* In other words, its prime factorization has no repeated factors.
6+
* Examples: 1, 2, 3, 5, 6, 7, 10, 11, 13, 14, 15...
7+
* Non-examples: 4, 8, 9, 12, 16, 18 (all divisible by 4 or 9)
8+
*
9+
* @see <a href="https://en.wikipedia.org/wiki/Square-free_integer">Square-free integer (Wikipedia)</a>
10+
*/
11+
12+
private SquareFreeInteger(){
13+
14+
}
15+
16+
/**
17+
* Checks if a given number is square-free.
18+
*
19+
* @param num the number to check(this must be positive)
20+
* @return true if num is square-free , false otherwise
21+
* @throws IllegalArgumentException if num is not positive
22+
*
23+
*/
24+
public static boolean isSquareFree(int num){
25+
if(num<=0){
26+
throw new IllegalArgumentException("Input must be a positive integer.");
27+
}
28+
29+
for(int i=2; (long)i*i<=num ;i++){
30+
if(num%(i*i)==0){
31+
return false;
32+
}
33+
}
34+
return true;
35+
36+
37+
}
38+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertFalse;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
import static org.junit.jupiter.api.Assertions.assertTrue;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
class SquareFreeIntegerTest {
10+
11+
@Test
12+
void testSquareFreeNumbers() {
13+
assertTrue(SquareFreeInteger.isSquareFree(1));
14+
assertTrue(SquareFreeInteger.isSquareFree(2));
15+
assertTrue(SquareFreeInteger.isSquareFree(3));
16+
assertTrue(SquareFreeInteger.isSquareFree(6));
17+
assertTrue(SquareFreeInteger.isSquareFree(15));
18+
}
19+
20+
@Test
21+
void testNonSquareFreeNumbers() {
22+
assertFalse(SquareFreeInteger.isSquareFree(4));
23+
assertFalse(SquareFreeInteger.isSquareFree(8));
24+
assertFalse(SquareFreeInteger.isSquareFree(9));
25+
assertFalse(SquareFreeInteger.isSquareFree(12));
26+
assertFalse(SquareFreeInteger.isSquareFree(18));
27+
}
28+
29+
@Test
30+
void testInvalidInput() {
31+
assertThrows(IllegalArgumentException.class, () -> SquareFreeInteger.isSquareFree(0));
32+
assertThrows(IllegalArgumentException.class, () -> SquareFreeInteger.isSquareFree(-5));
33+
}
34+
}

0 commit comments

Comments
 (0)