I’m working on a CodeWars problem that deals with steps between prime numbers. A step is how much separates the two primes within a range. Only the first two primes that match the step argument are returned as output.
For example, between 3 and 5 is a step of 2. The required input for the function is the step amount, the starting number of the range (inclusive), and ending number of the range (also inclusive). Again, the output would be the first two primes that are separated by the number of steps in the argument, but if no such primes exist within that range & step argument, then the result is null.
From there I have been able to create what seems like an appropriate solution, as it passes the initial tests, but during the actual attempt it fails the random tests. The random tests always fail on what seems like a 10 step input that it says should return null, but since the input isn’t shown, I can’t say what is wrong for sure.
Here is my code, thanks for any help spotting logic errors:
public static long[] Step(int g, long m, long n)
{
long first = 0;
long second = 0;
long check = 0;
for(int i = (int)m; i <= n; i++)
{
if(!IsPrime(i))
{
continue;
}
if(first == 0)
{
first = (long)i;
check = first + g;
if (IsPrime((int)check))
{
second = check;
break;
}
else
{
first = 0;
}
}
}
if (first == 0 || second == 0)
{
return null;
}
return new long[] { first, second };
}
public static bool IsPrime(int g)
{
if(g<=0)
{
return false;
}
for(int i = 2; i <= g - 1; i++)
{
if(g % i == 0)
{
return false;
}
}
return true;
}
I fail to see an error, but maybe you could try to tackle efficiency (for(+=2) and learn data structures (store found primes). Use a cursor to follow to get the correct distance.
I mean, your LISP like functional programming style is good. It is just maybe sometimes you want to vary it a bit.
What’s up with that insane cyclomatic complexity. Who uses continue anyways..
Some things:
Your IsPrime
function doesn’t handle an integer arg of 1 properly (1 is not prime), so I believe your code might inappropriately handle something like IsPrime(2, 1, 3)
; it should return null
, but would return [1, 3]
if I understand the details of the problem (and similar for other ranges containing 1).
As other person said about continue
, consider that these two things are the same:
if (!IsValid(n)) { continue; }
else { DoStuff() }
versus:
if (IsValid(n)) { DoStuff() }
(sorry, mobile formatting…)
What you did isn’t wrong, just needlessly verbose. Lastly, good job! Keep going! Remember to keep an eye out for edge cases; things tend to start breaking at the edges.
Fixed formatting.
Hello, xtecht: code blocks using triple backticks (“`) don’t work on all versions of Reddit!
Some users see this / this instead.
Your second isn’t checked if it is bigger than the allowed range.