以下是在C#中找到质数的两种方法。
using System; namespace Program { class Demo { public static void Main() { int n =7; int a; a = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { a++; } } if (a == 2) { Console.WriteLine("Prime Number"); } else { Console.WriteLine("Not a Prime Number"); } Console.ReadLine(); } } }
输出结果
Prime Number
using System; namespace Program { class Demo { static void Main(string[] args) { int n = 7; int res = primeFunc(n); if (res == 0) { Console.WriteLine("Not a prime number", n); } else { Console.WriteLine("Prime number", n); } Console.Read(); } private static int primeFunc(int n) { int i; for (i = 2; i <= n - 1; i++) { if (n % i == 0) { return 0; } } if (i == n) { return 1; } return 0; } } }
输出结果
Prime number