6 kyu
Is a number prime?
1,079 of 116,937arithmetric
Loading description...
Mathematics
Algorithms
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
In "C++" While pushing "Attempt" -7 or -6 turns "false" in test, but it is "true" for -7 (it is a prime number) and "false" for -6 (not prime)
Are you sure? Can you point to a resource which presents -7 as a prime number?
https://en.wikipedia.org/wiki/List_of_prime_numbers
I can see no -7 (i.e. "negative seven") on the list?
From your link:
-7 is neither natural nor greater than 1, so, no, it's not a prime number.
This "too slow" condition is stupid as hell for 6 kyu. If the code works, it should be accepted.
But it doesn't, does it? Because it's too slow. There is a performance requirement, if your code isn't fast enough, it'll only work for a certain range. It's written in the kata's description. You can complain about the rank, that's fine, but you can't say that your code works when it doesn't.
The rank is the only thing I'm mad about. I mean, 6 kyu is right next after "fundamentals" (which is 7-8), it's not fair to demand optimizations on this level.
6 kyu is considered OK for challenges with trivial optimisations. Yellow kata are not beginner level anymore.
You have to start working with optimizations at some point, and as hobovsky said, it's a very trivial one, in fact, if you read that part of the description again, you'll see this:
Pointing out where you should focus to make your code faster.
That is now the 3rd KATA, where my Code works in VS, but in CW some tests fail. My code is in c#. With the same numbers, I get differents results in VS and CW!!!!
I cannot speak to your two previous experiences, but in this case your code does not work for this kata, yet. Notice that your code passes the Sample Tests? That's because it is basically correct. Meanwhile, it times out for the Final Tests because it is not optimized enough to solve all the tests in sufficient time. This then speaks to the fact that your outside environment is not set up identically to test your code with adaquate coverage. It is then most likely also, in your two previous experiences, that your outside environment was caught lacking in a similar fashion. Often, it is as simple as the fact that there are certain edge cases / specific tests which are not present in the outside environment.
Thank you for the kata 🙏. Not sure if I like it very much though. It checks whether you know particular optimal methods for solving the challenge; solving the challenge is not enough :) Anyway, thanks!
I like it too
Почему 75 является false, если оно делится на 5, 1, 75, 25 и соответвенно не является простым
Если не является простым, то как раз и должно быть
False
, ещё раз почитайте условие заданияI get an error during the full check, even though the numbers that give an error are not prime and are also divisible by another number.
Please show which number failed in the c++ section
The 'attempt' keeps timing out for me.
Yes, it is possible. See the "Note on performance" in the description.
This comment has been hidden.
No, you can't submit unless you pass all the tests in the alotted time. You need a faster algorithm.
This comment has been hidden.
Not a kata issue. See https://docs.codewars.com/training/troubleshooting#post-discourse and https://docs.codewars.com/training/troubleshooting#timeout.
This comment has been hidden.
You do not need sieve for this kata, but the problem with your sieve is that you rebuild it every time for every test (also in a somewhat inefficient way), while it could just be built once and reused between tests.
There is no feedback on which numbers the test is passing and for which one it's failing in C++
Yes I'm in the same boat...
This comment has been hidden.
Ask yourself, if a number is divisible by
x
, then what is its remainder after the division ? ^^This Kata doesn't work for Python. In the random tests it returns that the number 1492952653 isn't prime. Is it a fail in the Kata or in my Code?
1492952653 is not prime:
1492952653 = 31 × 48159763
. The problem is with your code.C#. Why does "Attempt" time out? I extended the test script to include 30 of these:
yield return new TestCaseData(Random.Shared.Next(1, int.MaxValue)).Returns(true);
and multiple test runs completed in, and I quote:
Time: 4756ms Passed: 6Failed: 30Exit Code: 1
Time: 4578ms Passed: 6Failed: 30Exit Code: 1
Time: 6446ms Passed: 8Failed: 28Exit Code: 1
Time: 9301ms Passed: 9Failed: 27Exit Code: 1
Time: 8725ms Passed: 9Failed: 27Exit Code: 1
Time: 5229ms Passed: 7Failed: 29Exit Code: 1
yet "Attempt" constantly times out at 12s. It seems like "Attempt" runs considerablly slower than merely testing.
I will skip this kata :(
Well, I have some bad news: there seems to be ~1000 tests when you hit "Attempt".
The problem is that your solution is doing more work than it has to. Your
max
condition can be improved significantly :PThe problem is that with
Random.Shared.Next(1, int.MaxValue)
, your tests have a very high chance to be mostly meaningless: they will generate many numbers which are very easy to solve, and very few interesting numbers, which are more difficult to solve. For example, out of 30 numbers you generated, approx. 15 of them will be even numbers, which are trivial to solve.Your tests are not great, because they do not generate interesting inputs. Your solution is apparently also not great, because it's not able to solve the interesting inputs :)
In VS it works. But here no, i can't understand
This comment has been hidden.
First of all, your code is almost unreadable because it's all on one line. Format it properly as shown here https://docs.codewars.com/references/markdown/#code-block
Secondly, from description:
Why are you bothering with negative numbers then?
It also looks like you got some flawed logic in your
else
statement, but it's just a guess because, again, your code is unreadable right now.What does your function return for negative numbers like -3? Read the description again. Also, printing the input would help you debug your code.
This comment has been hidden.
Read about
sieve of eratosthenes
This comment has been hidden.
Your code being too slow is not a kata issue. Try using a faster algorithm. Read the Note in the description about performance btw.
I am having some trouble while attempting here is the full digonostic:
UndefinedBehaviorSanitizer:DEADLYSIGNAL ==1==ERROR: UndefinedBehaviorSanitizer: FPE on unknown address 0x0000004282b5 (pc 0x0000004282b5 bp 0x000000000000 sp 0x7fff12c7b420 T1) ==1==WARNING: invalid path to external symbolizer! ==1==WARNING: Failed to use and restart external symbolizer! #0 0x4282b4 (/workspace/test+0x4282b4) #1 0x42680e (/workspace/test+0x42680e) #2 0x4261dd (/workspace/test+0x4261dd) #3 0x425ecb (/workspace/test+0x425ecb) #4 0x42a8b5 (/workspace/test+0x42a8b5) #5 0x4256bd (/workspace/test+0x4256bd) #6 0x7fadcbda2c86 (/lib/x86_64-linux-gnu/libc.so.6+0x21c86) #7 0x4045f9 (/workspace/test+0x4045f9)
UndefinedBehaviorSanitizer can not provide additional info. ==1==ABORTING
Please use the
question
tag to ask for help, an issue is a provable bug within the kata. The error comes from your code; you use the modulo operator (%
) with0
as the right operand, this is undefined behavior (division by 0).Anything related to trial division is just lame. :P
really intersting
Loved it! Made me crack my brains for a good while as a beginner. Thanks :)
This is a very interesting kata. There are trivial answers, and then there are very difficult (and more efficient) answers which could utilize advanced number theory and/or combinatorics. It's amazing just how difficult counting problems can actually be.
this kata challenges more my code efficiency than the actual problem solving skill.
Code efficiency is a problem you have to solve.
Hello guys, to whom may have encoutered the execution time error. (Your codes take too much time to execute even though you solved the problem)
This made me come to realize that this platform codewars isn't about statistics or proving how master you are in coding. it's about learning and improving your programming skill. Therefore, It all comes down to "algorithm", the first 15 minute of this video https://www.youtube.com/watch?v=8hly31xKli0 will blow your mind.
it keeps saying timed out. -_- i am new can someone help me
Thanks, found my mistake. i need to make it better because its too slow
This comment has been hidden.
The kata works fine in Java (your language). Your code timing out is not a kata
issue
. You need to write a more efficient algorithm.Read the description:
And that's what your code does, so, no wonder it will fail.
sorry, i am quite new and now that i saw the solutions i get it. I would still leave the comment up, if others run in the same issue.
thanks
Hey , having issues with increasing efficiency to avoid a timeout error . Could I do so while still using list comprehension ? I tried converting to a generator but it doesnt seem to fix the issue . Any tips? this happens with a few of my programs
Generally speaking, this is about code efficiency. There may remain something about how you optomize that has not yet occurred to you.
You need a better algorithm than what you have now. Counting all factors is a very bad approach, and, on top of that, your implementation of counting all factors is very, very slow.Switching between loops and lists and comprehensions and generators is not going to help if you stick to your current algorithm.
This comment has been hidden.
This is a good challenge but I don't like getting punished for solving the problem the "wrong" way. The server timeout for basic code like this is frustrating but did cause me to re-think.
The way you mean is not quote wrong quote, it is LITERALLY wrong. As in, unacceptable. Solution which needs a minute or three minutes to complete, while it's EASILY possible to modify it and pass in a second (after just a slight modification, and not a total rewrite), fully deserves to be "punished" and rejected. That's the whole point of problem solving challenges.
Relax chief, its not that serious. Just because you pissed your pamper doesn't mean you get to invalidate my opinion as a beginner. I stand on what I said. Get over it.
Also you must not be able to read because I said it was a good challenge and it caused me to think in a different way. If you're so butthurt that you can't handle mild negative criticism then go ahead and downvote. It's my opinion.
Keep the echo chamber downvotes coming boys. Straight to the moon.
Hi, how can i optimize the performacje in c#?
without looking at your code I would guess that your code could be faster if it didn't loop quite so far
This comment has been hidden.
This comment has been hidden.
awesome! congrats
maybe it is intended but in R the function name that is writen in draft, is not what test calls.
This is actually an issue, I already rose is a long time ago.
You should write about performance requirement at the very top of your kata
This comment has been hidden.
No, they're not, please read the description again. Tests are fine, not a kata issue.
not really, -41 is not a prime number, but 41 is. Why? because 41 has to be divisible by itself or by 1. Which means that something has to exist to divide 41. To divide -41 you will have to divide it with quantities that do not exist. -1 for example is a sense can represent 'lack' of something rather than '1' which means something atleast exists 1 time.
prime is not a negative number
Why it is passing basic testcases and faiiling random due to timeout, even there is noo big loops going on. please let me know what is the issue
Please don't raise a kata
Issue
when you're asking aQuestion
. See https://docs.codewars.com/training/troubleshooting/#post-discourse.Your solution is too slow. See https://docs.codewars.com/training/troubleshooting/#timeout.
was a very good kata, would be helpful more kata like this where you need to find a better way for increasing the time speed of your algorithm.
This comment has been hidden.
Don't post solutions in the discourse. See https://docs.codewars.com/training/troubleshooting#post-discourse
Not a kata suggestion.
This comment has been hidden.
Please use appropriate formatting when posting code. See https://docs.codewars.com/references/markdown#code-block
It's not working because there are an infinite number of prime numbers, and your function can only correctly identify the first four.
If the kata doesn't give you sufficient debugging feedback, you can always print any values you find relevant. See https://docs.codewars.com/training/training-example#debugging-a-kata
Test only gives you like 4 test cases, and attempt gives you like a 100 test cases. The Test test cases are pretty simple but the Attempt test cases are tricky and try to find a way to fail your code if you are not careful enough. When it comes to your code, there are certain numbers that will not have a divisor from 2 to 9 but can have double digits divisors.
This comment has been hidden.
From the description:
This comment has been hidden.
This comment has been hidden.
OP left the building
I feel like this kata should be 5 kyu. Haha
Thanks for the suggestion, but the rank won't be changed once the kata is out of beta.
This comment has been hidden.
Hints aren't kata suggestions. Read this: https://docs.codewars.com/training/troubleshooting#post-discourse
Closing.
I think I misunderstood the description. Assumed looping was generally prohibited so I gave up. Alas, should've given it a shot regardless.
This comment has been hidden.
try % 197
Why asking ChatGPT and not someone who actually knows? https://www.wolframalpha.com/input?i=325207009
Now please someone tell me, should we expect a wave of "ChatGPT said that there's a bug in this kata" issues?
sry my bad
I dont know much but The very people who make AI functional cannot and should not verify their own work on AI, atleast not now, knowledge will be lost forever.......
had fun, I was a bit stuck on optimization but, found out a way that is not my usual brute force :) .
This comment has been hidden.
Read the note on performance, not a kata issue.
This comment has been hidden.
I can understand your wanting to be helpful, but AFAIK that's more than a hint because it informs too much towards the actual solution, so I have put the spoiler flag on your comment.
How to solve it without a loop?
Nobody said without a loop:
Reduce the number of cycles of your loop.
sorry didn't check you already solved it
This comment has been hidden.
not an issue, PHP can be solved in 1 second.
Please read the note:
And that's exactly what your code is doing. Not a kata issue.
Kata is perfectly solvable in PHP:
And the highest tested value for PHP is 9294972289. It doesn't say there are 2^31 tests, it says for some languages there can be tests where n is near 2^31.
"And that's exactly what your code is doing. Not a kata issue."
No, I certainly misspoke but my code does not loop to determine if the number is prime or not.
The loop I'm talking about is a test that runs the is_prime() function X times (which was empty for my duration tests)
But thank you for enlightening me on the description.
I'm not English and didn't realize (reading the description) that there weren't 2^31 tests to perform but in fact the highest number tested could potentially be as large as 2^31.
I understand better and I'm getting back on my code, on my algorithm to improve it and that it can process a number as big as 9294972289 in less than 12 seconds :)
And after reviewing my algorithm (after a little math lesson on how to determine a prime number), everything works fine.
Completed in 1303.11ms.
I will now see the solutions and see how this one can be improved.
And thank you again for the clarifications on the description (confusion between test number and largest test)
This took longer than expected
Can i speed up a algoritm when i use int.MaxValue and i had only 5,1 sec? but here i have always more than 12 sec?
I also have that issue with that runtime over 1200ms.
By the way, the times presented at testresult are incorrect, on top it says 502ms and below it says 0.5ms.
You offer no reason why this would be a kata problem and not a your code problem. You don't mention which of the 18 languages would have this problem.
Are you sure about that 1200ms? Most languages allow 12000ms.
Time on top is probably including all sorts of overhead; time below is probably just for running tests against your solution.
If you have problems, follow the troubleshooting guide in Docs. At the very end ( because you probably just should not ) it also tells you how to raise an issue, and what information to include.
Closing now.
Your solution does exactly the thing which is described in description as too slow.
This comment has been hidden.
Your solution returns incorrect answer for n=143.
A solution being incorrect is not a kata issue.
Thanks for answer. I forgot about it.
This comment has been hidden.
Read the description again, especially the NOTE on performance
This comment has been hidden.
This comment has been hidden.
Your algorithm does not check if a number is prime. I would suggest looking up a definition of a prime number.
Not a kata isue.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
I know, but unfortunately I also have to take this into account with an if statement. Or it doesnt solve numbers bigger than 10
nvm, im stupid. But still thx for the help ^^
This comment has been hidden.
Because your code is too slow:
This comment has been hidden.
This comment has been hidden.
IKR!
This comment has been hidden.
Not a kata issue, your current code passes that test, but it is too slow to pass the Attempt tests.
Read that part of the description again. Read the Troubleshooting guide too: https://docs.codewars.com/training/troubleshooting
It's difficult to say why your code works incorrectly if we don't even know what language you try, and what your code is. Post your code here (remember about code formatting and mark it as spoiler!) so we could take a look together and help you find your mistake.
This comment has been hidden.
This is interesting, because the solution you pasted passes for me all tests.
Can you show a screenshot of the code you try and its test result?
Why -5 is not prime number?
Please read the kata description.
I'm sorry, I thought we should make the numbers positive :)
prime numbers are natural numbers (i.e integers < 0). If we included negative numbers also, the fundamental theorem of arithmetic would not be able to hold that each natural number < 1 has a unique prime factorization.
I think you meant > 0 there.
What is this Random tests? I tried 2 options of solving and only Random tests is failing. Why? What kind of tests are there?
The random tests are just 1000 random numbers between 0 and
Int32.MaxValue
. Your solution doesn't cover all possible cases. You only check if something is divisible by 2, 3, 5, or 7... if it's not then you declare the number as prime. There are plenty of numbers which aren't divisible by those numbers but are divisible by other numbers. 361, for example isn't prime, but isn't divisible by any of those numbers.This comment has been hidden.
Hi @SerdarMut and welcome to Codewars (and happy new year!).
Please don't use Issue tag for problems with your code, it is reserved for serious kata problems.
Your code itself is very slow - in fact, for a prime number
n
, it will performn
operations. In your local computer, for example, run your code on this 8 digit prime number:62528561
and see how long it takes. You need to find a better approach.
This comment has been hidden.
This comment has been hidden.
Sure. Optimize it some more then. You only need basic optimizations to pass the kata. Code length has nothing to do with code's performance.
Your code being too slow is not a kata issue.
Feel free to explore https://docs.codewars.com/training/troubleshooting or ask for help on Discord server.
New translation for Scala. Review please.
https://www.codewars.com/kumite/637e3e59ef7bb8a35e16a2a8?sel=637e3e59ef7bb8a35e16a2a8
Thanks.
I passed all the test!! Alas!! I'm getting timed out(16000ms) while submission
Then you passed all the tests until your code timed out (there are more tests)
With Rust I get a timeout out of a "tests::random_tests". Unfortunately, the test is not provided.
Java submission test includes a failing test for -2147483647, which should not be prime, and my function does not mark it prime as far as I can tell. If I write this condition into the tests manually it succeeds.
That negative number you see there (not sure why) is not the input value of the test your code is failing, add
System.out.println(num + "\n");
to your function to see the input.Your code fails with input values like this one:
assertFalse("372436920 is not prime", Prime.isPrime(372436920));
and that's a problem with your code, not a kata issue.My suggestion for anyone having issues is to read the whole question. Especially the part where it says there is a number in the test designed to time you out with simpler solutions.
This comment has been hidden.
Your solution is not exactly a kata suggestion. Kata suggestions are ideas how to improve kata, and not how to sovle it.
This comment has been hidden.
Hi and welcome to Codewars - this error message means that your code/solution took too long; you need to find a better and more efficient algorithm.
(in some very rare cases it might be a server issue, so you can resubmit your solution just to check, but it's unlikely)
This comment has been hidden.
kata hint != kata suggestion
solving in C#, only random test is failing, does the test maybe have an error?
This comment has been hidden.
It works know, your pointer really helped me out, thanks!
I passed all the tests and my code timed out when it was time to submit... smh
Execution timed out, g++ and tests works perfectly even with 9 digit numbers
Your code being too slow is not a kata issue.
This comment has been hidden.
It's slow if done wrong. It should be fine if done correctly :)
This comment has been hidden.
the performance was lateing me.
This comment has been hidden.
A problem with your code is not a kata issue:
Your code is too slow.
YES THAT'S THE PROBLEM!! RANDOM TEST are really big numbers XD Incorrect answer for n=1423176763: False should equal True Incorrect answer for n=1108179043: False should equal True Incorrect answer for n=1239667097: False should equal True
As I said, the problem is your code is too slow.
It can't be faster , how can it be?? num=1423176763
My code passes all tests including the random ones:
Look for a faster algorithm, the one you're using does a lot of operations that aren't needed.
It's written in the kata's description too:
okay great , I'll think of another algorithm
there's some issues with this kata : 1/ prime numbers can be negative 2/ the random test is obviously giving big numbers that makes the compilation time out
1- Not with this definition:
2- Which language? Maybe your code is too slow.
Go translation
Approved
Maybe just remove this Kata? In Python the tests are stating that -5 and -41 are not prime. That's not correct.
I know that the definition they teach this is something like this: A prime is a positive integer p>1 that has no positive integer divisors other than 1 and p itself.
Negative numbers are excluded. In fact, they are given no thought. Wikipedia does the same. Notice how it's not mentioned that no negative number is a prime on the wiki page. It's simpler and for most purposes not addressing it works.
Now if you actually want to check if a negative number is a prime you should extend the definition to handle negative numbers.
https://en.wikipedia.org/wiki/Prime_number#Prime_elements_in_rings https://math.stackexchange.com/questions/1002459/do-we-have-negative-prime-numbers
Wikipedia's article first sentence is "A prime number (or a prime) is a natural number...". This excludes de facto negative integers. In the paragraph you mention: " The integers are a ring, and the prime numbers in the integers have been generalized to rings in two different ways,.." This is a generalization of prime numbers, and doesn't affect the definition of what is a prime number. Moreover, if anyone would have a doubt, the description clearly explains what must be considered a prime number in this kata. Removing the kata for this would just be ridiculous.
The generalization does affect the definition. Generalizing from the whole numbers to the integers (includes negative numbers) makes it natural to generalize the definition of primes. It's strange to do so since generalizing to complex numbers is more useful.
I read the description again. It leaves no ambuiguity, so the fault is on me. I just saw negative numbers and primes and assumed we would use a definition generelized to integers. I should have been more diligent before making an issue. My only excuse is that there are others.
Swift translation
Python test is broken: Traceback (most recent call last): File "/workspace/default/tests.py", line 3, in @Test.describe("Basic") NameError: name 'Test' is not defined. Did you mean: 'test'?
Not an issue, please reset the trainer in order to trigger latest version of tests
This comment has been hidden.
There is no reason why you should not use a loop.
This comment has been hidden.
Your code is wrong, it fails for example returning true for 25, which is obviously not a prime number. Please don't create an issue when your code doesn't work. Read this: https://docs.codewars.com/training/troubleshooting/
This comment has been hidden.
From wikipedia:
So
-5
and-41
which are not greater than one, are clearly not prime.datachap is right, Kacarott is wrong.
The rest of the paragraph on Wikipedia:
A natural number greater than 1 that is not prime is called a composite number. For example, 5 is prime because the only ways of writing it as a product, 1 × 5 or 5 × 1, involve 5 itself. However, 4 is composite because it is a product (2 × 2) in which both numbers are smaller than 4. Primes are central in number theory because of the fundamental theorem of arithmetic: every natural number greater than 1 is either a prime itself or can be factorized as a product of primes that is unique up to their order.
It only relates to natural numbers.
Asking to check if a negative number is a prime I would expect more diligence. It's not trivial. On wiki you want to check Prime elements in rings if you include negative numbers.
You could also go here: https://math.stackexchange.com/questions/1002459/do-we-have-negative-prime-numbers to learn more.
It's merely conventional, but if you admit that there are negative primes (or that
1
is prime BTW), you break the Fundamental theorem of arithmetic, which does more harm than good.This comment has been hidden.
you could try finding another algorithm thats faster than this
I am trying to implement the Slieve of Eratosthenes but I am not getting desired output
You don't need Sieve, just do less iterations in your original code
There is a problem with the -1 test when I run the code. On vscode all the tests work including the -1 except when I want to submit the code to validate the solution. Weird.
Here your code returns true for -1. And it also does that in repl.it.
Ok I found it thank you !
R: bad function name in solution set up:
prime_list
should beis_prime
.LC translation
( This translation modifies the description. )
Approved by some1
I am failing for returning false on if 12 is a prime number.
C++ tests are fine. Make sure you're not misreading the logs.
I just using printf("%i", num); at the very begining of the funcation to get that 12 number and it is telling me I failed after returning it as false, telling me it should be true. I am not sure what is going on if that is not the case. Must be a strange bug.
Use
printf("%i\n", num);
instead, that's not 12 as input, it's one test with 1 and another with 2.Yep that is it. That was embarrassing haha. Thanks for pointing it out!
This comment has been hidden.
Hint 1: try to think how your solution works for input in the form of
n = some_very_large_prime * 2
and think how to improve it.Hint 2: is the
if
in the last line really needed? Can you think of a way to get rid of it?This comment has been hidden.
Hi. See there how to format so it is somewhat readable: https://docs.codewars.com/training/troubleshooting/#post-discourse
Just an idea: Once you found a factor you know the result yet... And for negatives, it's easy to check first isn't it?
When I test my code I pass but when I Attempt I fail, I'm just gonna assume the compiler doesn't work
No, it's just your code isn't 100% right. Sample tests are just that, a sample of the full test suite. Read this: https://docs.codewars.com/training/troubleshooting
So, this is saying that my code is wrong because -5 ins't a prie number, but it is or am I dumb?
No, it isn't.
thank you , im stupid, i have been confused all day for this xD
I am getting the same error they are saying -5 is not a prime .
And they are right.
This comment has been hidden.
This comment has been hidden.
Did anyone attempt the code successfuly ??
Definitively not an issue. See there: https://docs.codewars.com/training/troubleshooting/
And to answer your question: yes, more than 69,000 persons did (see at the top of the page).
After you finish the kata, try this for fun Test number 12314567201 (prime) Test number 50991113171 (prime) Test number 50991113171 * 12314567201 (not prime) The last one takes forever to check. If you can find efficent method to solve the problem, post on a math forum to collect Nobel Prize
.
This comment has been hidden.
Guys what does is mean?
True should equal False None should equal False
My code only accepts 'int' type, in other case it would return False
The first value in the error message is what your function returned, not the input value. The other is the expected one.
I tried to change assertion messages, and I hope they are a bit clearer now.
ok, mathematitians have been trying to solve this problem for 2000 years, and I have to do it with c++
This comment has been hidden.
Your code being too slow is not a kata issue.
How long does your solution run for n=1853606873 ?
Yes you right, because my code take a lot of time to loop between (2) and (huge number) i should do some researching about this topic. thanks for your help
This comment has been hidden.
Not a kata issue, read this: https://docs.codewars.com/training/troubleshooting#print-input
"testRandom . Failed asserting that true matches expected false." , - How to pass this test?
I tried to improve some error messages. Please back up your solution, refresh the page, reset the trainer, and run tests again. They will still fail, but message should be clearer now.
Im timing out with close to maximum efficiency solution lol
Then look for doubly maximum efficient solution. Too slow solution is not a kata issue.
I honestly don't know what to do lol
Me too ,but I don't know how to solve the problem.
Random Tests are giving big numbers (billions), that's the reason of timing out
Is there someone who was able to attempt the Kata?
Details - Botom left you can see how many times it's been completed, the answer is yes.
This comment has been hidden.
This comment has been hidden.
Please read the description again:
Doesn't matter if wikipedia says so I mean it just isn't like I got the right solution I just don't think the test cases should be like that
And 1 is not a prime number: https://blogs.scientificamerican.com/roots-of-unity/why-isnt-1-a-prime-number/
I got it, two divisors needed
I'm having the timeout error too. The code is right but it gives me a timeout😐
This comment has been hidden.
Finally all tests passed.
Yes am getting this timeout error too
This kata has nothing to do with programming and code. The correct solution is to be found in math area and math area alone. Useless as >programming< task
I agree
What did you expect prime numbers be related to? Sports? Dancing? It's obvious it's a math related topic. But I disagree it has nothing to do with programming or coding. Finding if a number is prime or not the fastest possible way is programming related. Encryption (that uses prime numbers), is programming related.
Read the tags: ALGORITHMS MATHEMATICS NUMBERS
I don't understand your complain.
Also this showcases a problem where you have to find a more efficient solution than the most obvious one; which is important in quite a lot of cases.
It's about implementing efficient solution to given problem.
I have a time error with my code, but when i use it in pycharm with timer - it take almost zero time, cant understand what problem is, it work also even on a big numbers
Wouldn't it be better to make a recursive call that evaluates 3 times and if counter = 2 returns true instead of looping through n numbers?
In general recursion is slower than loop.
My solution is giving an error in the random test, but I can't understand how this test was done on top of my code.
Read this: https://docs.codewars.com/training/troubleshooting
Thanks, you helped me a lot.
This comment has been hidden.
Your solution is too inefficient, and you're most likely doing exactly what the description tells you not to. Not an issue.
This comment has been hidden.
How to avoid overtime? What if it's just the square of the prime in the range?
This comment has been hidden.
This comment has been hidden.
Tests are ok. Your code doesn't work, you need to learn to debug it, or learn what is a prime number, which is all but a confidential notion. See there for debugging: https://docs.codewars.com/training/troubleshooting/
This thread is spoiling the kata, I mark it with a spoiler flag.
thanks,maybe i need learn some algorithm,my problem is reduce the number of cycles and ensure that no special cases fail the test
This comment has been hidden.
Don't spoil solutions.
This comment has been hidden.
No, the tests are fine:
Your code isn't fast enough with the numbers used in the tests. Research how to make your code faster, maybe with another algorithm.
Thanks! I'll look into how to make it more efficient.
This comment has been hidden.
Posting your code publicly is prohibited. Not a suggestion.
This comment has been hidden.
Your approach is very inefficient. This is not a kata issue. See there: https://docs.codewars.com/training/troubleshooting/
thx for the link, but you can help me to understand why? in my machine "execution time : 0.021 s" and tests here allways says under 600ms.
Try a few tests with
n = 2000000000
or similar.This is a very classic mathematical problem, and an easy 6 kyu kata. You need to use another method, make an online search and you'll find easily. Any hint we could give you would spoil the solution.
Just one thing: to find out if a number is prime, you don't need all the primes below it. Actually you don't need any of them, you just need to check... it's prime.
@akar-0: I guess Eratostenes never thought of calculating such high numbers :S thx for the hint.
2000000000 is the maximum value tested in random tests in Python. On your computer you can only do the basic tests, which are easy and not numerous ones.
You seem to confuse primes generator with primarily test. Sieves are not tests, they are prime generators. To test for a prime you do not need prime generators. You could use one, but not in the most trivial way of generating all primes up to N.
This comment has been hidden.
Don't spoil solution on discourse page, thanks.
Very Good Kata ! i like it !!
This comment has been hidden.
Not a suggestion.
This comment has been hidden.
This comment has been hidden.
You should print the input to console, so you can see which test fails.
Thanks for the tips ! In the meantime, I've found the solution
This comment has been hidden.
No, your code is passing some tests until it times out. There are more tests.
That's in the description. And it is what's happening with your code.
Thank you!
This comment has been hidden.
No, it's not a primer number with that definition.
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
well done !
kata hint != kata suggestion
This comment has been hidden.
What does your code return for n=31, and why?
This comment has been hidden.
And for 143?
This comment has been hidden.
Found my problem. Thanks for helping me!
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
Hello! Thanks for your answer! = 3 I'll take a deeper look
Oh, I see :c It is really stupid mistake, I'm sorry that didn't see it before. My bad, I will improve. Thanks a lot! P.S: WORKS!
여기에 한국 성님들없나요? 개어려움 좀 가르쳐주셈.. 뉴비한테 코드최적화 넘 어려운거 아님? 아니 이건 수학을 잘해야하는 거임? 아니면 알고리즘 사고 방식이 잘못된거임???? 둘 다 못하는데 어떡하라는 겁니까 ㅠㅠ
It's not question about optimization here, it is basic math. No need to be good at math. This is a (very easy) 6 kyu, only the most naive solutions won't pass, it is not exagerated at all. It's very easy to find a working solution with a single research online.
Also, please post in English or almost nobody will be able to understand you. You can use a translator and you should be majoritarily understood.
This comment has been hidden.
This is very very very very very far from being necessary here...
This comment has been hidden.
This is one of the most classic math problems. I won't give you any hint, it's something easy to find on the internet, just search with the name of the kata...
It's a pity! I'm going to find solution myself anyway : ) Thanks!
I trust that you can do it! You were on the way to implement the Miller-Rabin's primality test, that seems an excellent exercise (I never did it myself)! At last I'm confident you'll learn a lot solving this kata, and you'll remember it!
This comment has been hidden.
same issue here
This comment has been hidden.
1: Please read the description:
1 is not greater than 1.
2: It doesn't require so much optimization, 6 kyu is fine.
This comment has been hidden.
COBOL translation
approved
This comment has been hidden.
This comment has been hidden.
It's written in the instructions: "NOTE on performance: There are no fancy optimizations required, but still the most trivial solutions might time out. Numbers go up to 2^31 (or similar, depends on language version). Looping all the way up to n, or n/2, will be too slow."
It says basically that there are huge numbers so you need to optimise your code to run faster. If you check every number, or only half of them it will fail.
you may need to change the start and end parameters in the loop
This comment has been hidden.
Not a kata issue, read the note in the kata's description and the post below yours. Make your code faster.
Well, as a newbie who spent seven hours on this problem and later found it out, here are some tips for those who pass their basic tests, but fail in attempt (Execution Timed Out: 12000/16000 MS).
Good Luck. Even if you copy the right code, please understand the computational logic behind it. Thanks.
Not actually kata suggestion, closing. Regarding your points, there is no reason not to use for loops, most of the solutions use it. Just a fun fact: in python for loops are actually faster than while loops :p
wait while loops are faster than for loops?
Nope. For loops are faster and this has to do with how these two constructs have been implemented in Python and to what extent they rely on C Also, solving this kata with a for loop should work perfectly fine.
This comment has been hidden.
Especially after trying a lot of things on your own, is good to check google as well from time to time :)
i finally got and then figured out 2 ways to solve it shortly after this. was a matter of one small miscalculation.
I am in the exact same position. I've tried counting up, counting down, seemingly all that I can think of.
This comment has been hidden.
This comment has been hidden.
I am interesting whether anyone did this through elliptic curves? I was too lazy for something like that.
Any link to read about it? Thanks.
https://en.wikipedia.org/wiki/Elliptic_curve_primality#Example_of_Atkin%E2%80%93Morain_ECPP
If you would like to learn more about elliptic curves per se, I can recommend this article: https://web.archive.org/web/20210513235048/https://andrea.corbellini.name/2015/05/17/elliptic-curve-cryptography-a-gentle-introduction/
Hi guys, I struggled with this problem because it timed out every time until I found the solution.
There are several ways to find the prime numbers, but if you want to pass the time out issue focus on this 2 things:
Good luck!
Thanks for tips
yes, thanks... Im still strggling, have tried several different attempts. 12000ms seems to be the threshold. I will give it another go with your sugestions and see if i can do it.
This comment has been hidden.
what does your solution return for n=9?
This comment has been hidden.
Interesting way to prevent us from making unneficient code xD Nice kata :)
This comment has been hidden.
its difficult to tell exactly whats wrong without seeing your code, but FPE could mean some arithmetic error like division by zero or maybe domain error of some function like log or pow or sqrt.
Seeing your code could help to find the problem.
This comment has been hidden.
Your code performs division by 0.
oh im so dumb -.- thx now is the only problem the timeout but i think i can figure it out
this kata deserve to be deleted ! its attempt in js is irrelevant after all optimization it gives run out- its written that it might do this but still you cant know in attemp if the code is right! didnt like it
Please, improve your code, and read the note about performance.
Is it normal for code to work perfectly in ide on my pc but not in the kata? it keeps saying 3 & 5 return false. Tried it myself in codeblocks and it worked just fine. bothe return true.
Please read this: https://docs.codewars.com/training/troubleshooting/
No answer after a week, vague issue, kata works fine in C++, closing.
Execution Timed Out everytime after testing
You need to find a more efficient approach.
Your solution timed out because you're checking more cases than you need to. Think about at what number the checks start to be redundant. : )
This comment has been hidden.
You need to find a more efficient approach.
Well, my algorithm works but it times out. Am I doing anything wrong?
please see this paragraph: https://docs.codewars.com/training/troubleshooting/#timeout
This comment has been hidden.
True
(the Boolean truth value) is not the same as'True'
(the string that represents the word "True").I think this Kata requires knowledge of primes that is not relevant to learning computer algorithms.
How can there be knowledge of primes that is not relevant to learning computer algorithms, when some of the brightest mathematicians and computer scientists of all time have been advancing our knowledge of primes, algorithms and computers, for decades; from Alan Turing evaluating the Riemann Zeta Function on Manchester University's Mark I computer in 1950, to Shor's algorithm for quantum computing in 1994? Having said that, it might be worth taking a step back, and asking is there a way to solve this kata without more than trivial contact with the mathematics of primes? What libraries does the language you are using include? Does that help?
Yeah you are probably right
This comment has been hidden.
Please don't spoil solutions. This is absolutely basic math, users who are not familiar with it have to search a minimum to find a working solution, not read the Discourse page... This is a 6kyu (and yet, an easy one), if you give this information you give the key to the problem and it becomes as trivial as a 8 kyu. There is a reason why this hint is not in the description.
i totally agree
This is what I get when I click Test Test Results: PrimeTest testNotPrime testBasic testPrime Completed in 13ms You have passed all of the tests! :)
but when I click attempt I get : Execution Timed Out (16000 ms)
It means your code is either too slow, or it gets lost with some values and never finishes. Check it out, this one is not difficult, just check what is needed.
In the problem description it mentions that iterating up to n or n/2 will be too slow. If this is what you're doing, consider shortening the range on your loop (hint: the upper limit should be the largest factor of n, a value that involves fractional exponents).
I am able to make the test pass for is prime. I am also able to make it pass for is not prime based on the boolean value I pass into my conditional. But if I try using a else if check or a second if conditional to check the result I can't do both. So...I am guessing because I use a return statement I am exiting ealry or something maybe. Still not figued it out.
Once you know if it is a prime, you also know if it is not a prime (!), so you can return the result immediately (I don't know which language you're using but you can give a variable the boolean value, for example: isPrime= True or False; return isPrime... If that's not even clear for you you should train on easy katas 7/8 kyus to practice that).
I think this is too difficult for 6kyu, rather closer to 4kyu.
No, 6 kyu is ok.
This is really basic maths stuff, the kata does not require real optimization, many 7 kyus are harder :)
If the problem required a more efficient solution then I would agree with Danil, but getting a brute force solution to this is not terribly difficult.
Very interesting kata! Thanks!
It would be really nice if a hint on what to research was given. Im passing the test but fail the random one. Also, how do I see the parameters that fail? Am I not supposed to know what fails the test...
Look for what is a prime number. This is really basic maths. The test fails when you return true if the parameter is not a prime or false and the parameter is a prime. You can print the parameter on the console, but the way to do it depends on the language you are using.
This comment has been hidden.
There are infinitely many prime numbers, your method is not a good one. How are you going to check that, for example, 169 (13*13) is not prime this way? You need to find another way, it's easy to find.
.
Everyone in the comments seems to agree that negative numbers aren't prime. The definition given in the description: "Per Wikipedia, a prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself." Is valid for negative numbers (e.g. -5 has divisors: 1, 5, -1, -5 i.e. the only positive divisors are 1 and itself), I think the language "positive divisors" makes it clear they're considering negative numbers here.
Regardless of what common usage is, I think the definition should match the test cases. Clarifying the definition would be an easy fix.
Is -5 a natural number? The definition you quoted mentions natural numbers. Are negative numbers such?
Even if -5 was a natural number (which it isn't):
You're right! Not a close reading on my part.
my test output is showing weird errors it says 75 not prime:true should equal false 4 not prime : true should equal false.this also happened for other numbers like 6 and 8...i mean 4,6,8and 75 are definitely not prime numbers pls fix this
Your code is returning
True
instead ofFalse
for those numbers that aren't prime numbers, the tests are ok, your code is wrong.but the real issue here is my other tests are passed (for prime numbers) the test is considering non prime numbers as prime numbers
would there be anyway i could send u the test output?
This comment has been hidden.
После того, как решил задачу по зеленной кнопке, дальше переходить к другой? Или ещё чего нажимать надо для учета решения?
This comment has been hidden.
You do not ned to import JUnit if you have problems with it. You can just add
main
and callPrime.isPrime(4)
from it.This comment has been hidden.
That's a problem with your code, not a kata issue, you're testing too many divisors.
This comment has been hidden.
This one passes 453 tests but fails 66
This comment has been hidden.
Изпользуй утверждение, что наименьший делить составного числа не более корня этого числа. Пропиши данное условие и время на проверку огромных чисел сократится в огромнократно.
This comment has been hidden.
And what happens when you step through your code with debugger locally in your IDE?
I didn't run it in an idle, because when I created a folder in visual studio it didn't allow me to creat a java file in it on intellij now can you please help me?
and junit wouldn't import
OP solved it, closing
This comment has been hidden.
First of all, be careful when disclosing your solution or approach in the discourse. Even if it doesn't work, you risk spoiling the fun for others who are trying to discover methods of their own.
Secondly, inputs go up to 2^31 as stated in the description. Iterating over that range is bound to fail, as worst case complexity is O(n) (the number may be prime). Dealing with primes generally requires a slightly more sophisticated approach. I recommend just doing some research; a good starting point is here.
How long does your program run for
1992104689
? How long does it run for1999999817
?Если на тест рандом не хватает времени, что это значит? Задача зачтена, или надо придумывать что-то пошустрее?
the compiler timed out after having passed the first test and it needed me to optimize my code
Yes, you've to optimize your code. (BTW Issue tags are only supposed to be used when you think something is wrong in the problem itself, and is independent of your code)
Any R coder that uses return() at the end of their function should automatically fail the test.
I'm glad I never took a job interview in front of you ;-)
This comment has been hidden.
How much memory I've been given ? /////////////////// java.lang.OutOfMemoryError: Java heap space at Prime.isPrime(Prime.java:11) at PrimeTest.testRandom(PrimeTest.java:92) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at org.junit.runner.JUnitCore.run(JUnitCore.java:115) at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:39) at org.junit.vintage.engine.VintageTestEngine$$Lambda$132/1846412426.accept(Unknown Source) at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184) at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193) at java.util.Iterator.forEachRemaining(Iterator.java:116) at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151) at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174) at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
You ask wrong questions, fellow adventurer. Ask the right question, and you will find the answer.
And the right question is: how much memory you consume?
How many numbers are there in the test set ? My solution timed out after checking 261 numbers :))
There will be around 1000 numbers to check, I was pretty far the first time :)
for those who passing the test, but fail at attempt. The num you will be attempting against is huge, so try to do something about that before running your loop checks.
im passing all the test, but my test result is always: Execution Timed Out
Then you're not passing all the tests, you passed all the test until it timed out, improve your algorithm.
This comment has been hidden.
This comment has been hidden.
A hint: there are at least two functions available from importable modules that you can use directly.
This comment has been hidden.
Exactly this part is meant to be the main point of the kata, and I consider getting to this conclusion to have the most educational effect. I think it's worth for the users to spend some time to get to this by themselves.
I am going to mark your post as spoiler, so others do not miss the fun of getting to the solution :)
This comment has been hidden.
No, it means your solution is too slow.
https://github.com/codewars/codewars.com/wiki/Troubleshooting-your-solution#i-get-execution-timeout-why
This comment has been hidden.
This comment has been hidden.
If you tell me the language I will double check, but I can assure you that tests do not go beyond signed int, which would be ~2e9, for almost all languages. Test suite is tuned to pass all tests in below 4 seconds with the almost-trivial, most basic solution (but not worse, i.e. not totally naive).
If your solution needs 800ms for a single number then it's too much, because there's 1000 numbers tested.
This comment has been hidden.
It looks like you're doing too many repeating calculations. Do you really need a Vec for this?
Multithreading and other optimization techniques are an overkill for this particular kata. I am not sure what purpose exactly the
prime_numbers
vector has, but the way it's processed atm causes your problems.This comment has been hidden.
I special cased the loop increment to 2 after a threshold and doubled the number of random number evaluations from 30 to 60 but still times out.
Looking at primes from 1..100 shows 25 primes with prime gap deltas of 2,4,6,8. I am not sure how to be systematic in this effort. Is there a paper someone can direct me to?
Richard This is approximately logarithmic?
Expected complexity is a bit worse than logarithmic, but much better than linear. Linear solution will not pass, but it's very easy to come up with much more performant solution than linear.
Do not focus on the loop step, step of 2 is perfectly OK, but step of 1 would also pass the kata. More improtant is the upper bound of your loop. Try to figure out how far you need to loop, and at what point you are perfectly sure that you do not need to loop any further.
My solutions either run into memset (bool) space or runtime exceeded. The straightforward wiki dfn causes runtime exceeded (attached below).
My for loop upper bound increment is i++. Maybe it can be dynamically trimmed to avoid visiting multiples of existing primes?
**Is that the right direction towards a solution? **
Random_Test
1 num:876527174 .. is not prime! 21 num:1577810551 .. is not prime!
2 num:1644030750 .. is not prime! 22 num:1266333403 .. is not prime!
3 num:1393969603 .. is not prime! 23 num:2132127515 .. is not prime!
4 num:1335491684 .. is not prime! 24 num:1281074547 .. is not prime!
5 num:1929713169 .. is not prime! 25 num:90046948 .. is not prime!
6 num:24193965 .. is not prime! 26 num:2068897426 .. is not prime!
7 num:49651675 .. is not prime! 27 num:1737718634 .. is not prime!
8 num:218588094 .. is not prime! 28 num:714922702 .. is not prime!
9 num:356028242 .. is not prime! 29 num:162692740 .. is not prime!
10 num:877418047 .. is not prime! 30 num:587217759 .. is not prime!
11 num:901310737 .. is not prime! 31 num:869667984 .. is not prime!
12 num:1107801141 .. is not prime! 32 num:1039219915 .. is not prime!
13 num:2099772465 .. is not prime! 33 num:83764861.. IS prime!
14 num:993022361 .. is not prime! 34 num:116153939 .. is not prime!
15 num:503688437 .. is not prime! 35 num:227227951 .. is not prime!
16 num:735156648 .. is not prime!
17 num:1089112823.. IS prime!
18 num:914354483 .. is not prime!
19 num:390465283 .. is not prime! STDERR
20 num:1819589577 .. is not prime! Execution Timed Out (12000 ms)
Good thing is that your solution is rather correct, because it returns correct answers.
Bad thing is that it's too slow, and manages to pass ~35 random tests out of 1000. You need to think how to improve performance, but it might be easier than you think. This kata does not require memoization, and your solution will pass even if it performs separate calculations for every input. You just need to figure out how high your loop should go before being certain that the number is (or is not) prime.
My code passes the test, but it times out when i try to send it. I don''t know how to measure how long it takes in my IDE to run it, but it looks like it works instantaneously. I just pasted 15-digit square number into sample test, it completed in 7402ms. What is in the main test if 12000ms is not enough time?
This comment has been hidden.
This comment has been hidden.
This comment has been hidden.
If it times out, your code didn't pass all the tests, please, read the note about performance in the kata's description.
me too.
If the kata "passes all tests, but times outs", it means that your solution returns correct answers, passes some amount of tests, but it's too slow and is not able to pass all of the tests in time.
It passes some, but there are still some more left.
same thing happen to me where can i see the time on screen?
when you try the test, there is info "Completed in ..." under the window where you put your code there is sample test. you can change it, for example type some big prime number instead of existing prime. you will see how long it takes when you run the test.
This comment has been hidden.
Your solution passes 19 tests and then it fails:
Not related to your problem, but, what's this:
Math.floor(0)
? That's the same as0
Your solution returned that -5 is prime, but it's not this is the error i am reciving but -5 is prime number.The test should expect a true result.
Similar issues were already raised. This kata uses the very common definition of a prime as a natural number. -5 is not a natural number, so it's not a prime by this interpretation.
See this.
Dude -5 is not a prime number since -5 has 2 factors -1 & 5
You could say (almost) the same for 5, no, that's not the reason, the only reason is the definition says a prime number is a natural number greater than 1.
ohh now its clear.Thanks
"There are no fancy optimizations required"
LIE
Why?
Read the whole sentence please.
Are we really testing programming anymore? Runtime performance is an advanced topic.
Yes. It's pretty improtant to create programs which give you answer on the same day you asked.
On C++, I pass all tests but I fail whenever I attempt it. The test I fail says that it is expecting true, but my function returns false. However when I log the number that I am failing on it says that it is 12, which is obviously not prime, so shouldn't a return of false be correct? Any suggestions?
I've just checked the C++ version, and it seems to be OK. I did not find any problem with it, my solution passes as expected.
You could read this paragraph to double check that you interpret logs correctly, because sometimes they can be confusing to get right.
If you think that your solution is 100% correct, post it here (see how), so we could take a look.
This comment has been hidden.
This comment has been hidden.
It probably does not fail on 12. It passes a test case for 1, and fails on the test case for 2. You print 1 and 2 without a new line, so they look like 12.
This comment has been hidden.
Not an issue. Your code is too slow.
Not exactly, your code passes all tests until it times out, there are more tests.
This comment has been hidden.
Your solution returns invalid answer for 121 or 143.
This comment has been hidden.
Thank you, hobovsky and max30272. Also, I was using C++. I will be sure to include that info next time.
I'm passing all the test cases, but when I go to click Attempt I get this error I've never seen before. Anybody have any idea what I might be doing wrong? (This is in C++ btw.)
UndefinedBehaviorSanitizer:DEADLYSIGNAL ==1==ERROR: UndefinedBehaviorSanitizer: FPE on unknown address 0x000000427e77 (pc 0x000000427e77 bp 0x7ffe78df1c10 sp 0x7ffe78df1750 T1) ==1==WARNING: invalid path to external symbolizer! ==1==WARNING: Failed to use and restart external symbolizer! #0 0x427e76 (/workspace/test+0x427e76) #1 0x42672e (/workspace/test+0x42672e) #2 0x4260fd (/workspace/test+0x4260fd) #3 0x425deb (/workspace/test+0x425deb) #4 0x42a8f5 (/workspace/test+0x42a8f5) #5 0x4255dd (/workspace/test+0x4255dd) #6 0x7f0401267bf6 (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6) #7 0x404529 (/workspace/test+0x404529)
UndefinedBehaviorSanitizer can not provide additional info. ==1==ABORTING
FPE on ...
suggests that you have an arithmetic error somewhere, possibly division by 0.This comment has been hidden.
This comment has been hidden.
Not a kata issue.
Your soluton is too slow, your loops probably go too high.
This comment has been hidden.
Sorry for the identation
Your loop goes too high. You can make much fewer iterations.
Your solution being too slow is not a kata issue.
in the test my program takes 0.28ms but when i try to send it appears "Execution Timed Out (12000 ms)". Why is this happening ?. I have no idea how to further optimize my code ...
they may run multiple samples.
same things is happening to me
me too!
As far as i understand there are over a 1000 numbers and they all have to be checked in below 12 second time limit.
Pascal translation
approved
Able to run same solution in my local with 0.82s but submitting get execution timeout error ??
Yes, it's possible.
How long does your solution run in your local IDE for
n=1807015081
?IsPrimeNumber.isPrime(1807015081) test run successfull in 0.135s, using java8 IntStream.rangeClosed.
For some reason when I run my code for Tests it works well and it passes all tests in ~1600ms, but I get the following error when I click on attempt:
"FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory"
I'm using JS as my language. Have anyone faced this issue and what it really means? When I was doing some testing on Codepen during development it all worked well for me as well.
This comment has been hidden.
If sample test take 1.6s, it's highly probable your solution is too slow.
This comment has been hidden.
This code definitely doesn't cause an 'allocation failed' error, for you aren't even working with arrays. Your solution is correct, but it's still too slow. You need to do less iterations somehow.
Your loop goes too high.
Thank you!
This comment has been hidden.
Your solution is too slow. Not an issue.
i have failed my master...🥷🏻
This comment has been hidden.
they're already both included in
num < 2
my guess is you changed something else as well, and that perhaps you're attributing the difference to the wrong change? ..seems to me like that would be the same amount of lines since you're replacing the condition with another onein your current solution you're testing for
< 2
twice maybe you were incorrectly converting negative numbers to positive ones? but you'd never do that, because if it's negative then it's not prime and there is nothing more to do. maybe you were turning something that was less than 2 into something that was greater than 2, defeating the comparison.OP solved it, closing
This comment has been hidden.
I am a complete R noob so I might be missing something, but I am not sure if I agree and would appreciate being educated here :)
I managed to solve the kata in R implementing the almost-trivial algorithm, with no real optimization. No sieves, no theorems, no memoization, no nothing. As expected, it passed the tests.
Granted, it takes longer than I'd expect. I do not know if it's a feature of R or something is wrong with tests, the test suite runs unexpectedly long for input set which is 10 times smaller in size and 100 times smaller in values than other languages. But even then, I get quite consistent time of ~8 seconds, which is quite OK. Ideally it would be ~4 seconds, so maybe I'd tune the inputs somehow, but still, unoptimized solution without any complex algos takes 8s of available 12s. More than desired, but far from the edge.
Since the soluton based on sub-linear algorithm without any kind of optimizations or any special approach consistently passes the tests, I consider the difficulty ranking correct. What am I missing here?
Two years and no answer. Closing.
This comment has been hidden.
Please read this: https://github.com/codewars/codewars.com/wiki/Troubleshooting-your-solution#post-discourse (I see you've already been told to do it, but, read the part aboout formatting and marking your post as having spoiler content, please).
About your problem, you need to return a boolean, not a string like you did.
Do you know the difference between
True
and"True"
?This comment has been hidden.
Last bullet point of this paragraph of FAQ describes your problem.
Read this paragraph too.
Not a kata issue.
This comment has been hidden.
This comment has been hidden.
oh man.. I missed that.. thank you
Having the same problem. How did you solve that?