当前位置:网站首页>【C语言】每日一题,求水仙花数,求变种水仙花数
【C语言】每日一题,求水仙花数,求变种水仙花数
2022-08-11 07:15:00 【零玖零】
1. 求出0~100000之间的所有“水仙花数”并输出。
“水仙花数”是指一个n位数,其各位数字的n次方之和确好等于该数本身,如:153=1^3+5^3+3^3,则153是一个“水仙花数”。
#include <stdio.h>
#include <math.h>
int main()//求水仙花数
{
int a = 0;
int mai = 0;
for (a = 0; a < 100000; a++)
{
int b = a;
int c = 0;
int sum = 0;
while (b>0)
{
c++;//利用c统计a的位数
b/=10;
}
b = a;
while (b > 0)
{
int ca = (int)pow(b % 10, c);//pow是用来求次方的库函数,其返回值是double类型
sum += ca;
b /= 10;
}
if (sum == a)
{
printf("%d ", a);
mai++;
}
}
printf("找到水仙花数个数为%d\n",mai);
}
此处我们用到了一个库函数pow,它的作用是求x的y次方。头文件math.h。当然也可以自己写一个函数去实现不必过于纠结。
其返回类型是一个double类型,在使用的过程中要注意, double pow(double x, double y)。
二、变种水仙花数 - Lily Number:把任意的数字,从中间拆分成两个数字,比如1461 可以拆分成(1和461),(14和61),(146和1),如果所有拆分后的乘积之和等于自身,则是一个Lily Number。
例如:
655 = 6 * 55 + 65 * 5
1461 = 1*461 + 14*61 + 146*1
求出 5位数中的所有 Lily Number。
#include <stdio.h>
int main()
{
int a=0;
for(a=10000;a<100000;a++)
{
int sum=0;
int b=a;
int cj=10;
while(b>=10)
{
int k=a%cj;
b/=10;
sum += k*b ;
cj*=10;
}
if(sum==a)
printf("%d ",a);
}
return 0;
}
思路
以12345为例,我们需要求出1*2345+12*345+123*45+1234*5值与12345进行比较,所以我们可以让12345/10得到1234,%10得到5.除以100的到123,模上100的到45.除以1000的到12,模上1000的到345.沿着这个思路我们很简单就可以得到一个代码。然后我们只要加一个循环让它遍历我所想要找的区间就得到了答案。
此题属于简单题,巧用除跟模便可以解决。
边栏推荐
- 1.2-误差来源
- Pico neo3 Unity Packaging Settings
- matplotlib
- matplotlib
- 无服务器+域名也能搭建个人博客?真的,而且很快
- 【LeetCode】Summary of linked list problems
- Hibernate 的 Session 缓存相关操作
- 1046 划拳 (15 分)
- 【latex异常和错误】Missing $ inserted.<inserted text>You can‘t use \spacefactor in math mode.输出文本要注意特殊字符的转义
- tf.cast(), reduce_min(), reduce_max()
猜你喜欢
随机推荐
2022-08-10 Group 4 Self-cultivation class study notes (every day)
TF中的四则运算
How Unity programmers can improve their abilities
1051 Multiplication of Complex Numbers (15 points)
囍楽云任务源码
3.2-分类-Logistic回归
1091 N-自守数 (15 分)
3.1-Classification-probabilistic generative model
The most complete documentation on Excel's implementation of grouped summation
break pad源码编译--参考大佬博客的总结
年薪40W测试工程师成长之路,你在哪个阶段?
软件测试常用工具的用途及优缺点比较(详细)
Item 2 - Annual Income Judgment
数仓开发知识总结
TF中的条件语句;where()
1.2-误差来源
经典论文-MobileNet V1论文及实践
CSDN21天学习挑战赛——封装(06)
1046 划拳 (15 分)
1036 跟奥巴马一起编程 (15 分)