Data_Structure/Vorlesungen/DS/Beispiele/narcissistic-number.c

74 lines
1.1 KiB
C
Raw Normal View History

2025-01-20 21:25:33 +08:00
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
void convert(int n, int base)
{
if (n < base) {
printf("%d",n);
return;
}
convert(n/base,base);
printf("%d",n%base);
}
*/
void convert(int n, int base)
{
int digit;
if (n < base) {
if (n < 10)
printf("%d",n);
else
printf("%c",'A'+(n-10));
return;
}
convert(n/base,base);
digit = n%base;
if (digit < 10)
printf("%d",digit);
else
printf("%c",'A'+(digit-10));
}
int ArmstrongNumber(int n, int base)
{
static int i = -1, index = 0;
int j, k, p, r;
for (i++; index < n; i++) {
for (j = i, k = 0; j > 0; k++) j = j/base;
for (j = i, r = 0; j > 0;) {
p = j%base;
j = j/base;
r += (int)pow(p,k);
}
if (r == i) {
index++;
return i;
}
}
}
int main()
{
int base, howMany, n;
printf("\n<EFBFBD><EFBFBD><EFBFBD>X<EFBFBD>e<EFBFBD>X<EFBFBD>Ӫ<EFBFBD><EFBFBD>i<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ơH=> ");
scanf("%d",&howMany);
printf("\n<EFBFBD><EFBFBD><EFBFBD>J<EFBFBD><EFBFBD><EFBFBD><EFBFBD>(<=16) => ");
scanf("%d",&base);
puts("\n<EFBFBD>ŦX<EFBFBD><EFBFBD><EFBFBD>󪺼Ʀr<EFBFBD>p<EFBFBD>U");
for (n = 1; n <= howMany; n++) {
printf("#%d\t",n);
convert(ArmstrongNumber(n,base),base);
putchar('\n');
}
return 0;
}