0

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.

Zachish
  • 11
  • 1
  • you can use cancellation token for that purpose – tym32167 Oct 06 '20 at 21:51
  • 3
    That's when everybody clicks the close button of the console window. – Hans Passant Oct 06 '20 at 21:51
  • 1
    Zachish: While I agree that that's mostly a duplicate, the question that was marked as the target is pretty advanced. I have a feeling that you need something more basic, and a bit more elaborate intro. If that's the case [I wrote one here](https://gist.github.com/quetzalcoatl/10ce9806d97551b8e4a89b4e2d7b9132) since the post is closed and I can't post it as an answer. – quetzalcoatl Oct 06 '20 at 22:31

0 Answers0