Determine the prime number to implement bool IsPrime (int number), boolisprime

Source: Internet
Author: User

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

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.