I have a challenge on a programming platform (CodeWars - "Find the divisors") and my algorithm seems to be too slowly. This is error which I get from platform: Process was terminated. It took longer than 12000ms to complete
This is instructions for challenge: Create a function named divisors/Divisors that takes an integer and returns an array with all of the integer's divisors(except for 1 and the number itself). If the number is prime return the string '(integer) is prime' (null in C#)
public static int[] Divisors(int n /* out int numfactors*/)
{
List<int> divArray = new List<int>();
int div;
if (isPrime(n))
{
return divArray.ToArray();
}
else
{
for (div = 2; div < n / 2 + 1; div++)
{
if (n % div == 0)
{
divArray.Add(div);
}
return divArray.ToArray();
}
}
}
public static bool isPrime(int n)
{
int d = 2;
if (n == 1 && n % 2 == 0 && n != 2) return false;
while (d * d <= n)
{
if (n % d == 0) return false;
d = d + 1;
}
return true;
}
What i'm doing wrong, how I could optimize this algorithm? If I test a prime number, my code return "nothing" this I think it's another problem. if the number is prime, and I'm trying to return null my program crashes with : "Object reference not set to an instance of an object"