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