給定任一個各位數字不完全相同的4位正整數,如果我們先把4個數字按非遞增排序,再按非遞減排序,然后用第1個數字減第2個數字,將得到一個新的數字。一直重復這樣做,我們很快會停在有“數字黑洞”之稱的6174,這個神奇的數字也叫Kaprekar常數。
例如,我們從6767開始,將得到
7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...
現給定任意4位正整數,請編寫程序演示到達黑洞的過程。
#include<iostream>
#include <algorithm>
using namespace std;
void dele(int &n)//建立一個函數
{
int a[4]={0};
for(int i=0;i<4;i++)//將四個數字分開
{
a[i]=n%10;
n=n/10;
}
int max,term;//排序
for(int i=0;i<4;i++)
{
max=i;
for(int j=i+1;j<4;j++)
{
if(a[max]>a[j])
continue;
else
max=j;
}
if(max!=i)
{
term=a[i];
a[i]=a[max];
a[max]=term;
}
}
int p,q;
q=a[0]+a[1]*10+a[2]*100+a[3]*1000;
p=a[3]+a[2]*10+a[1]*100+a[0]*1000;
printf("%04d - %04d = %04d\n",p,q,p-q);
n=p-q;
}
int main()
{
int n;
cin>>n;
while(n!=6174 && n!=0)
dele(n);
return 0;
}
以下代碼摘自:FlyRush
#include <iostream>
#include <algorithm>
using namespace std;
int compare(const int &a, const int &b){
return a>b;
}
int main(){
int n;
scanf("%d", &n);
if(n % 1111 == 0){
printf("%d - %d = 0000\n", n, n);
return 0;
}
else{
int tmp = n;
while(true){
char c[5] = {'0','0','0','0','\0'};
int a, b;
for(int i = 3; tmp != 0; i--){
c[i] = (tmp % 10) + 48;
tmp /= 10;
}
sort(c, c + 4, compare);
a = (c[0] - 48) * 1000 + (c[1] - 48) * 100 + (c[2] - 48) * 10 + (c[3] - 48);
printf("%s - ", c);
sort(c, c + 4);
b = (c[0] - 48) * 1000 + (c[1] - 48) * 100 + (c[2] - 48) * 10 + (c[3] - 48);
printf("%s = ", c);
tmp = a - b;
printf("%04d\n", tmp);
if(tmp == 6174){
break;
}
}
}
return 0;
}