自娱自乐的小题目(2)

题目:判断101-200之间有多少个素数,并输出所有素数。 
1.程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除, 
则表明此数不是素数,反之是素数。

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test2 {
    class Program {
        //【程序2】 
        //题目:判断101-200之间有多少个素数,并输出所有素数。 
        static void Main(string[] args) {
            int count = 0;
            for (int i = 101; i < 201; i++) {
                if (primeNumber(i)) {
                    Console.WriteLine(i + "");
                    count++;
                }
            }
            Console.WriteLine("一共有{0}个素数", count);
        }
        static bool primeNumber(int n) {
            bool a = true;
            if (n < 2) {
                a = false;
            } else {
                for (int i = 2; i < (int)Math.Sqrt(n); i++) {
                    if (n % i == 0) {
                        a = false;
                        break;
                    }
                }
            }
            return a;
        }
    }
}

 

原文地址:https://www.cnblogs.com/socialdk/p/2518766.html