当前位置:网站首页>【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.沿着这个思路我们很简单就可以得到一个代码。然后我们只要加一个循环让它遍历我所想要找的区间就得到了答案。
此题属于简单题,巧用除跟模便可以解决。
边栏推荐
- 2021-08-11 For loop combined with multi-threaded asynchronous query and collect results
- CSDN21天学习挑战赛——封装(06)
- 1096 大美数 (15 分)
- tf.reduce_mean()与tf.reduce_sum()
- 1.2-误差来源
- 通过记账,了解当月收支情况
- 【sdx62】XBL设置共享内存变量,然后内核层获取变量实现
- The growth path of a 40W test engineer with an annual salary, which stage are you in?
- The most complete documentation on Excel's implementation of grouped summation
- How Unity programmers can improve their abilities
猜你喜欢
The growth path of a 40W test engineer with an annual salary, which stage are you in?
MindManager2022全新正式免费思维导图更新
Serverless + domain name can also build a personal blog? Really, and soon
1036 跟奥巴马一起编程 (15 分)
1076 Wifi密码 (15 分)
接口测试的基础流程和用例设计方法你知道吗?
2.1 - Gradient Descent
JRS303-数据校验
The easiest trick to support quick renaming of various files
Conditional statements in TF; where()
随机推荐
动态代理学习
【latex异常和错误】Missing $ inserted.<inserted text>You can‘t use \spacefactor in math mode.输出文本要注意特殊字符的转义
1081 检查密码 (15 分)
2022-08-09 Group 4 Self-cultivation class study notes (every day)
Four startup modes of Activity
基于微信小程序的租房小程序
【LeetCode】链表题解汇总
6月各手机银行活跃用户较快增长,创半年新高
Unity开发者必备的C#脚本技巧
1081 Check Password (15 points)
1061 判断题 (15 分)
囍楽cloud task source code
1106 2019数列 (15 分)
4.1 - Support Vector Machines
Two state forms of Service
Decrement operation in tf; tf.assign_sub()
Find the latest staff salary and the last staff salary changes
Pytorch模型转ONNX模型
1061 True or False (15 points)
数仓开发知识总结