循环结构的题
本帖最后由 琪琪怪怪 于 2020-11-13 14:31 编辑这道题怎么做??
水仙花数是指一个n位正整数(3<=n<=7),它的每个位上的数字的n次幂之和等于它本身。例如:1^3+5^3+3^3=153。 本题要求编写程序,计算所有n位水仙花数。 本帖最后由 baige 于 2020-11-13 15:12 编辑
#include <stdio.h>
typedef unsigned long long int ull;
ull ksm(ull a, ull n){
ull ans = 1;
while(n){
if(n&1){
ans *= a;
}
a *= a;
n >>= 1;
}
return ans;
}
int main(void){
int n;
scanf("%d",&n);
int start = ksm(10,n-1), end = ksm(10,n);
for(int i = start; i < end; ++i){
int sum = 0, temp = i;
while(temp){
// a%b = a-a/b*b
int t = temp - temp/10*10;
sum += ksm(t,n);
temp /= 10;
}
if(sum == i){
printf("%d\n",i);
}
}
return 0;
} 本帖最后由 风过无痕1989 于 2020-11-13 15:12 编辑
三位数的才叫水仙花数,四位数的叫玫瑰花数
// 输出水仙数花
#include <stdio.h>
int main()
{
int bai, shi, ge, n;
printf("result is: ");
for(n = 100;n < 1000;n++ )/*整数的取值范围*/
{
bai = n / 100;
shi = (n - bai * 100) / 10;
ge = n % 10;
if(n == bai * bai * bai + shi * shi * shi + ge * ge * ge)/*各位上的立方和是否与原数n相等*/
printf("%d", n);
}
printf("\n");
return 0;
}
// 输出玫瑰花数
#include <stdio.h>
int main()
{
int qian,bai, shi, ge, n;
printf("result is: ");
for (n = 1000;n <= 9999;n++)/*整数的取值范围*/
{
qian = n / 1000;
bai = (n - qian * 1000) / 100;
shi = (n - qian * 1000 - bai * 100) / 10;
ge = n % 10;
if (n == qian * qian * qian * qian + bai * bai * bai * bai + shi * shi * shi * shi + ge * ge * ge * ge)/*各位上的立方和是否与原数n相等*/
printf("%d", n);
}
printf("\n");
return 0;
} #include<stdio.h>
int main()
{
int n;
scanf("%d",&n);
if(n==3)printf("153\n370\n371\n407\n");
if(n==4)printf("1634\n8208\n9474\n");
if(n==5)printf("54748\n92727\n93084\n");
if(n==6)printf("548834\n");
if(n==7)printf("1741725\n4210818\n9800817\n9926315\n");
return 0;
} #include <stdio.h>
int main(){
int n, temp, sum, i;
int pow = {{0,1,4,9,16,25,36,49,64,81,100},\
{0,1,8,27,64,125,216,343,512,729,1000},{0,1,16,81,256,625,1296,2401,4096,6561,10000},\
{0,1,32,243,1024,3125,7776,16807,32768,59049,100000},\
{0,1,64,729,4096,15625,46656,117649,262144,531441,1000000},\
{0,1,128,2187,16384,78125,279936,823543,2097152,4782969,10000000}};
scanf("%d",&n);
for(i = pow; i < pow; ++i)
{
temp = i;
sum = 0;
while(temp)
{
sum += pow;
temp /= 10;
}
if(sum == i){
printf("%d\n",i);
}
}
return 0;
} 不要用math库的pow函数,很消耗时间,自己写一个就可以过评测系统了
#include <stdio.h>
typedef unsigned long long int ull;
ull pow(int a, int n){
ull ans = 1;
for(int i = 1; i <= n; ++i){
ans *= a;
}
return ans;
}
int main(void){
int n;
scanf("%d",&n);
int start = pow(10,n-1), end = pow(10,n);
for(int i = start; i < end; ++i){
int sum = 0, temp = i;
while(temp){
// a%b = a-a/b*b
int t = temp - temp/10*10;
sum += pow(t,n);
temp /= 10;
}
if(sum == i){
printf("%d\n",i);
}
}
return 0;
}
页:
[1]