Bug & Performance improvement
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 51
- Forks
- 1
- PR merge metrics
- No merged PRs in 30d
Description
You code is already really fast, which is awesome. Nevertheless you could improve the performance with some simple changes. No idea why nobody already suggested that.
Bug:
Your way to check if the given argument is a number is clever but does not catch all possible types of arguments. The following arguments are possible:
prime(-2) == False
prime(1) == False
prime(2) == True
prime(1.5) == True <-- Wrong
prime(Infinity) == False
prime(undefined) == False
prime(NaN) == False
prime('a') == False
prime("a") == False
prime([]) == False
prime([2]) == True <-- Wrong
prime([1,2]) == False
I suggest you to use Number.isInteger() to make sure the given argument is definitely an existing integer. It is supported by default by all browsers.
Performance:
- l.7: Instead of calculating the square of every possible divisor you could calculate the integer-square root just once, which may increase the runtime for small but should reduce the runtime for large numbers
for (var i = 5, j = Math.round(Math.sqrt(num)); i <= j; i += 6) {
- l.7/8: for every iteration you do 2 additions
i + 2andi + 6, even thoughi+2andi+4are sufficient, has a very small influence on performance and may already be done by the compiler
for (var i = 5, j = Math.round(Math.sqrt(num)); i <= j; i += 4) {
if (num % i === 0) return false;
i += 2;
if (num % i === 0) return false;
}
Hope i can help.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the prime-checking function and inspect the argument validation and divisor loop around lines 7-8. Confirm the behavior for the listed inputs, then ensure non-integers and non-numbers are rejected and the proposed divisor-loop changes preserve correct prime results and improve large-number performance.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- tooling
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 48/100