A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李建龙 中级黑马   /  2013-6-10 21:00  /  2527 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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);
        }
    }
}

1 个回复

倒序浏览
值得学习ing!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马