当前位置:网站首页>【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.沿着这个思路我们很简单就可以得到一个代码。然后我们只要加一个循环让它遍历我所想要找的区间就得到了答案。
此题属于简单题,巧用除跟模便可以解决。
边栏推荐
猜你喜欢
随机推荐
项目2-年收入判断
2021-08-11 For loop combined with multi-threaded asynchronous query and collect results
通过记账,了解当月收支情况
Serverless + domain name can also build a personal blog? Really, and soon
1056 组合数的和 (15 分)
【Pytorch】nn.Linear,nn.Conv
One-hot in TF
1051 Multiplication of Complex Numbers (15 points)
Distributed Lock-Redission - Cache Consistency Solution
【sdx62】XBL设置共享内存变量,然后内核层获取变量实现
1076 Wifi Password (15 points)
Write a resume like this, easy to get the interviewer
js判断图片是否存在
3.2-分类-Logistic回归
囍楽云任务源码
My creative anniversary丨Thank you for being with you for these 365 days, not forgetting the original intention, and each is wonderful
为什么我使用C#操作MySQL进行中文查询失败
【LeetCode每日一题】——844.比较含退格的字符串
1061 判断题 (15 分)
项目1-PM2.5预测