C#程序检查数字是否为质数
为了计算数字是否为质数,我们使用了for循环。在每次迭代的过程中,我们使用if语句查找数字本身之间的余数等于0。
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
a++;
}
}还添加了一个计数器a,如果数字是质数,即1和数字本身,则计数器a只会增加两次。因此,如果a的值为2,则表示该数字为质数。
示例
让我们看一个完整的例子来检查数字是否为质数
using System;
namespace Demo {
class MyApplication {
public static void Main() {
int n = 5, a = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
a++;
}
}
if (a == 2) {
Console.WriteLine("{0} is a Prime Number", n);
} else {
Console.WriteLine("Not a Prime Number");
}
Console.ReadLine();
}
}
}输出结果
5 is a Prime Number
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短