Determine the prime number to implement bool IsPrime (int number), boolisprime
1. Input a number repeatedly to determine whether it is a prime number. Is the input q over? Determine the prime number using methods to implement bool IsPrime (int number)
1 static void Main (string [] args) 2 {3 // required: repeatedly ask the user to enter a number to determine whether the number is a prime number. The input q ends? Determine the prime number using methods to implement bool IsPrime (int number) 4 Console. writeLine ("enter a number (enter q to exit):"); 5 string str = Console. readLine (); 6 while (str! = "Q") 7 {8 int num; 9 while (! Int. tryParse (str, out num) 10 {11 Console. writeLine ("You just entered not a number, Please re-enter (enter q, exit):"); 12 str = Console. readLine (); 13 if (str = "q") 14 {15 return; 16} 17} 18 bool result = IsPrime (num); // call the method, determines whether it is a prime number 19 if (result) 20 {21 Console. writeLine ("{0} is a prime number", num); 22} 23 Console. writeLine ("enter another number (q exit)"); 24 str = Console. readLine (); 25 26} 27 28 29 Console. readKey (); 30} 31 32 public static bool IsPrime (int number) 33 {34 bool result = true; 35 for (int I = number-1; I> 1; I --) 36 {37 if (number % I = 0) // if division is possible, it is not the prime number 38 {39 result = false; 40} 41} 42 43 return result; // pay attention to the return position. If an error occurs in the for loop, it cannot be ---- "return value" 44 45}
View Code