I wanted to know if there was any way I could cause a method to "time-out" or stop executing if nothing is returned. For example, in the code provided below, I'm passing a BigInteger through a method that determines if an integer is probable prime or not. When I call the method, I am using an array of Big Integers to test the method several times.
class PrimeChecker {
public static bool isPrime(BigInteger num) {
if (num <= 1)
{
return false;
}
if (num == 2)
{
return true;
}
for (int i = 3; i <= num / 2; ++i)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
}
}
However I am running in to an issue where some instances of num, such as:
35201546659608842026088328007565866231962578784643756647773109869245232364730066609837018108561065242031153677 (is Prime)
are stuck calculating in what feels like forever. Is there a way, either in my main or in the class itself, that I can stop this function after a certain period of time and move on to the next Big Integer in the array.
*I understand that the class itself may not be perfect and is most likely what is causing this test to be looping forever. However, I just wanted to see if there was any way to stop the function if it is calculating for x seconds/minutes.