C#l练习(用方法来实现:①判断一个给定的整数是否为“质数”。②计算1-100之间的所有质数(素数)的和


用方法来实现:判断一个给定的整数是否为“质数”

代码实现:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//用方法来实现:判断一个给定的整数是否为“质数”
namespace ConsoleApplication8
{
    class Fa
    {
        public static void prime(int a)
        {
            int c = 0;
            for (int i = 2; i <= Math.Sqrt(a) + 1; i++)
                if (a % i == 0)
                {
                    c = 1;
                    Console.WriteLine("该数不是质数");
                    break;
                }

            if (c == 0)
            {
                Console.WriteLine("该数是质数");

            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        { int a;
            Console.WriteLine("请输入一个数");
             a=Convert.ToInt32(Console.ReadLine());
              Fa.prime(a);
              Console.ReadKey();
        }
    }
}

实现结果:

计算1-100之间的所有质数(素数)的和。

代码实现:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class Fa
    {
        public static void prime()
        {      
          
            int sum=0;
            for(int j=2;j<=100;j++)//遍历1-100的数
            {  int c = 0;
                for (int i = 2; i < Math.Sqrt(j) + 1; i++)//判断是否为质数
                if (j % i == 0)
                {
                    c = 1;
                    break;
                }

            if (c == 0)//标记数
            {
                Console.WriteLine("{0}  ",j);
                sum += j;
            }

 

            }
            Console.WriteLine("1-100的素数和为{0}", sum);

        }
    }
    class Program
    {
        static void Main(string[] args)
        { 
              Fa.prime();
              Console.ReadKey();//外部调用方法
        }
    }
}

 

实现结果:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM