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