.Net基础篇_学习笔记_第七天_计算质数(找出0-100以内说有质数)

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 第六天_流程语句
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             //找出100以内的所有质数,质数只能被1和它本身整除的数,质数从2开始。 7  7%2 ,7%3 , 7%4 , 7%5, 7%6
14             int sum = 0;
15             for (int i = 2; i <= 100; i++)
16             {
17                 bool b = true;
18                 for (int j = 2; j <i; j++)
19                 {
20                     if (i % j == 0)
21                     {
22                         b = false;
23                         break;                                                          //除尽了,也就没必要继续往下取余的必要了。
24                     }
25                 }
26                 if (b)
27                 {
28                     Console.WriteLine(i);
29                     sum += i;
30                 }          
31             }
32             Console.WriteLine("所有质数的和为{0}",sum);
33             Console.ReadKey();
34         }
35     }
36 }

求质数是算法中,最简单的算法。

posted @ 2017-07-21 10:53  MR_L先生  阅读(387)  评论(0编辑  收藏  举报