C# 求素数/卡布列克运算

1. 用循环求1~100之间的所有素数,显示并输出结果。

using System;

usingSystem.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Q1

{

    class Program

    {

        static void Main(string[] args)

        {

          for (int i = 2; i <=100; i++)

            {

                for (int j = 2; j <= i; j++)

                {

                    if (i % j == 0 &&i!=j)

                        break;

                    if (i % j == 0 &&i== j)

                        Console.WriteLine(i);

                }

              

            }

            Console.ReadKey();

        }

    }

}

 

 

 

 

2.编程实现卡布列克运算,是指任意一个四位数,只要它们各个位上的数字不同,就有这样的规律。

一:把组成这个四位数的四个数从大到小排列,组成一个最大四位数。

二:把组成这个四位数的四个数从小到大排列,组成一个最小四位数。

三:求出以上两个数之差,得到一个新的四位数。重复上述的过程,最后得到的结果是6174.

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

usingSystem.Text;

usingSystem.Threading.Tasks;

 

namespacesjss102

{

    class Program

    {

        public static int e, f, g, h;

 

        public void Fenge(int n)

        {

 

            int a = n / 1000;

            int b = (n - a * 1000) / 100;

            int c = (n - a * 1000 - b * 100) /10;

            int d = n - a * 1000 - b * 100 - c* 10;

            e = a;

            f = b;

            g = c;

            h = d;

 

        }

        //排序  得到最小四位数

        public int Paixuxiao(int n)

        {

            Fenge(n);

            int[] k = new int[4] { e, f, g, h};

            Array.Sort(k);

            e = k[0];

            f = k[1];

            g = k[2];

            h = k[3];

           return (e * 1000 + f * 100 + g * 10 + h);

        }

 

        //排序 得到最大四位数

        public int Paixuda(int n)

        {

            Fenge(n);

            int[] k = new int[4] { e, f, g, h};

            Array.Sort(k);

            e = k[0];

            f = k[1];

            g = k[2];

            h = k[3];

            return (h * 1000 + g * 100 + f * 10+ e);

        }

 

 

        static void Main(string[] args)

        {

            Program test = new Program();

            int n = int.Parse(Console.ReadLine());

        

            do

            {

 

                int a = test.Paixuda(n);

                Console.WriteLine("排序后的最大数为{0}",a);

                int b = test.Paixuxiao(n);

                Console.WriteLine("排序后的最小数为{0}",b);

                n = a - b;           

                Console.WriteLine("当前数为{0}", n);

            } while (n != 6174);

 

            Console.WriteLine(n);

            Console.ReadKey(); 

               }

 

        }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章