-
-
Notifications
You must be signed in to change notification settings - Fork 362
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Function to check a number is Square free (#94)
* Update DIRECTORY.md * feat: Function to check a number is Square free * Update DIRECTORY.md Co-authored-by: autoprettier <[email protected]>
- Loading branch information
1 parent
c609dab
commit b1ac5d6
Showing
3 changed files
with
40 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/** | ||
* @function isSquareFree | ||
* @description A number is said to be square-free if no prime factor divides it more than once, i.e., the largest power of a prime factor that divides n is one. | ||
* @param {number} n - A number. | ||
* @return {boolean} - True if given number is a square free. | ||
* @see https://www.geeksforgeeks.org/square-free-number/ | ||
* @example isSquareFree(10) = true | ||
* @example isSquareFree(20) = false | ||
*/ | ||
|
||
export const isSquareFree = (n: number): boolean => { | ||
|
||
if (n < 0) throw new Error("number must be a natural number > 0"); | ||
if (n % 2 === 0) n = n / 2; | ||
if (n % 2 === 0) return false; | ||
|
||
for (let i: number = 3; i < Math.sqrt(n); i = i + 2) { | ||
if (n % i === 0) { | ||
n = n / i; | ||
if (n % i === 0) return false; | ||
} | ||
} | ||
return true; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { isSquareFree } from '../is_square_free'; | ||
|
||
describe('isSquareFree', () => { | ||
test('should return correct boolean value', () => { | ||
expect(isSquareFree(1)).toBe(true); | ||
expect(isSquareFree(10)).toBe(true); | ||
expect(isSquareFree(20)).toBe(false); | ||
expect(isSquareFree(26)).toBe(true); | ||
expect(isSquareFree(48)).toBe(false); | ||
}); | ||
}); |