C语言计算任意位数的水仙花数

一、水仙花数定义:

水仙花数(Narcissistic number)是指一个 n(n≥3) 位数,它的每个数位上的数字的 n 次幂之和等于它本身。例如 3 位数的 153:1³ + 5³ + 3³ = 153

二、C语言计算任意位数的水仙花数代码

c 复制代码
#include<stdio.h>

long int TenPower(int power)		// 计算 10 的 power 次幂
{
	if(power == 0){
		return 1;
	}
	long int result = 1;

	for(int i = 0;i < power; i++){
		result *= 10;
	}
	return result;
}	

int NumPower(int base, int power)		// 计算 base 的 power 次幂
{
	if(power == 0){
		return 1;
	}

	int result = 1;
	for(int i = 1; i <= power; i++){
		result *= base;
	}
	return result;
}

int main(void)
{
	int dig;				// 保存位数
	long int result;		// 保存次方计算结果
	
	puts("请输入位数(三位以上):");			// 根据水仙花数的定义,需要 3 位数及以上
	scanf("%d",&dig);
	if(dig < 3){
		puts("错误!位数必须为2以上!");
		return 0;
	}

	printf("%d位数的水仙花数有:", dig);
	for(long int i = TenPower(dig-1); i <= (TenPower(dig)-1); i++){			/* 根据给出的位数,拟定计算范围。
																			   如 3 位数计算范围为 100 ~ 999 */
		long int tmp = i;
		result = 0;
		for(int j = 1; j <= dig; j++){					// 计算每一位数字的 dig 次方
			result += NumPower(tmp/TenPower(dig-j), dig);			// 计算每一位数的 dig 次幂之和。例如计算 999 每一位的 dig 次幂之和
			tmp = tmp%TenPower(dig-j);								/* tmp 意为临时,便于计算每一位上的数字。
																	   例如计算 999,则首先计算 999/100 得到百位上数字为 9,
																	   然后 999%100 得到 99,然后 99/10 得到十位上数字为 9,
																	   然后 99%10 得到 9,然后 9/1 得到个位上数字为 9. */
		}
		if(i == result){					// 若该数字每一位数的 dig 次幂之和等于该数字,则为水仙花数
			printf("%ld ", i);
		}
		if(i == (TenPower(dig)-1)){			// 计算结束,换行符号
			puts("");
		}
	}

	return 0;
}

三、运行结果

相关推荐
RuoZoe2 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_5 天前
C语言内存函数
c语言·后端
norlan_jame7 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874757 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237177 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish7 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人7 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J7 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹47 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow7 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法