输出水仙花数
输入一个正整数n(3<=n<=7),输出所有的n位水仙花数。水仙花数是指一个n位正整数,它的各位数字的n次幂之和等于它本身。例如153的各位数字的立方和是1^3+5^3+3^3=153.试着编写程序。 本帖最后由 傻眼貓咪 于 2021-10-25 21:35 编辑#include <stdio.h>
#include <stdbool.h>
#include <math.h>
bool isNarcissistic(long long m, int n){
long long a = m, b, sum = 0;
while(a > 0){
b = a%10;
sum += pow(b, n);
a /= 10;
}
return sum == m ? true : false;
}
int main(){
int n; // (3 <= n <= 7)
scanf("%d", &n);
for(long long i = pow(10, (n-1)); i < pow(10, n); i++){
if(isNarcissistic(i, n)){
printf("%lld\n", i);
}
}
return 0;
}4
1634
8208
9474 本帖最后由 jackz007 于 2021-10-25 21:35 编辑
n = int(input())
if 3 <= n <= 7:
d = 10 ** (n - 1)
for x in range(d , d * 10) :
m , e , k = 0 , d , x
while e:
m += (k // e) ** n
k %= e
e //= 10
if m == x:
print(x)
运行实况:
D:\00.Excise\Python>python x.py
3
153
370
371
407
D:\00.Excise\Python>python x.py
5
54748
92727
93084
D:\00.Excise\Python> jackz007 发表于 2021-10-25 21:33
运行实况:
浅谈水仙花数题目
https://fishc.com.cn/thread-192863-1-1.html
(出处: 鱼C论坛)
柿子饼同学 发表于 2021-10-25 21:53
浅谈水仙花数题目
https://fishc.com.cn/thread-192863-1-1.html
(出处: 鱼C论坛)
有何指教? 本帖最后由 jackz007 于 2021-10-25 22:12 编辑
原来是 C 语言问题
#include <stdio.h>
int main(void)
{
int c , d , e , i , k , m , n , x ;
scanf("%d" , & n) ;
if(n >= 3 && n <= 7) {
for(d = i = 1 ; i < n ; i ++) d *= 10 ;
for(x = d ; x < d * 10 ; x ++) {
for(m = 0 , k = x , e = d ; e ; k %= e , e /= 10) {
for(c = 1 , i = 0 ; i < n ; i ++) c *= k / e ;
m += c ;
}
if(x == m) printf("%d\n" , x) ;
}
}
}
编译、运行实况:
D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
3
153
370
371
407
D:\00.Excise\C>x
5
54748
92727
93084
D:\00.Excise\C> 傻眼貓咪 发表于 2021-10-25 21:16
{:5_110:} jackz007 发表于 2021-10-25 22:06
有何指教?
不不不 , 就是跟个帖{:10_277:}
页:
[1]