4 ms·
One can kinda tell by looking at the code that the author hasn't written code professionally. At least not for very long.
by kyberias 11y ago
One can kinda tell by looking at the code that the author hasn't written code professionally. At least not for very long.
- goldenkey 11y agoSeems like prime will be getting set to false redundantly instead of short-circuiting. Optimizing compilers will catch this. Also not a good test considering that different CPUs might see this with branch prediction, and the results will vary.
- kyberias 11y agoI'm not quite sure whether compiler optimizations could catch that. How could they? Returning false on the first zero remainder is a different algorithm.
- goldenkey 11y agoIts the same result. Compilers only need to produce the correct behavior. Algos arent part of that when optimizations take hold.
- tyleo 11y agoI'm not sure there is a basis for this assumption. If there is I can't see one. I also can't see why it would matter. Edit: Makes more sense with the additional responses.
- spriggan3 11y agowhy ? because the function prime doesn't return when the if condition is false ?
- dang 11y agoPersonal swipes are not welcome on Hacker News. If you know more, use your superior knowledge to teach people, not put them down. Explaining what can be improved—simply, without snark—would help many of us learn, and would likely evoke an interesting discussion from others.
- deleted 11y ago[deleted]
- briHass 11y agoIt doesn't matter much for his test, because the compiler won't optimize it, but one can simplify the loop to only go from 2...n/2+1 e.g. change the line to: for(int a=2; a<n/2+1; a++) That would be the obvious optimization, since 2 is your smallest factor, a factor can't be larger than half your number. In actuallity, knowing a little math gives you that if a factor is > the square root of n, there's a factor smaller than that. So: for(int a=2; a<sqrt(n)+1; a++)
- occamrazor 11y agoAnd it would be better to move the sqrt(n) calculation outside of the loop (I guess that any decent compiler would make this simple optimisation anyway)
- briHass 11y agoYeah, that would only be evaluated once, since the value of n doesn't change inside the loop.
- nivertech 11y agoI think it should be something like: test for all even numbers only once + uint last = ceil(sqrt(n)); for(uint a=3; a<=last; ++a,++a)