C# 1000以内所有素数
for语句:
using System;
using System.Collections.Generic;
using System.Text;
namespace sushu
{
class Program
{
static void Main()
{
int j,n=0;
Console.WriteLine("输出1000以内的所有素数:");
for (int i = 2; i <=1000; i++)
{
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
break;
}
if (j > i / 2)
{
n += 1;
Console.Write("{0}\t",i);
}
}
Console.WriteLine("\n");
Console.WriteLine("统计共有:{0}个数", n);
}
}
}
while语句:
using System;
using System.Collections.Generic;
using System.Text;
namespace sushuwhile
{
class Program
{
static void Main()
{
int i = 2, j, n = 0;
Console.WriteLine("输出所有的素数:");
while (i <= 1000)
{
j = 2;
while (j <= i / 2)
{
if (i % j == 0)
break;
j++;
}
if (j > i / 2)
{
n += 1;
Console.Write("{0}\t", i);
}
i++;
}
Console.WriteLine("\n");
Console.WriteLine("统计共有:{0}个数", n);
}
}
} |
|