《水仙花数》

什么是水仙花数?

         水仙花数(Narcissistic number)也被称为超完全数字不变数(pluperfect digital invariant, PPDI)、自恋数自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),水仙花数是指一个 3 位数,它的每个数位上的数字的 3次幂之和等于它本身。例如:1^3 + 5^3+ 3^3 = 153。

        简单来说,水仙花数它的每个数位上的数字的 3次方之和等于它本身。

难点

      这道题目中,最难的就是分解各个数位。

上代码

C++版

//一:C++中水仙花数实现代码
#include<iostream>
using std::cout;
using std::endl;
#define f(a) (a)*(a)*(a)
int main() {
    for (int i = 100;i < 1000;i++)
        if (f(i % 10) + f(i / 10 % 10) + f(i / 100 % 10) == i)
            cout << i << endl;
    system("pause");
    return 0;
}
//二:C++中任意位数水仙花数实现代码
#include<iostream>
#include<cmath>
using namespace std;
int main(])
{
    long n1, n2, a;
    int i;
    cout << "请输入Narcissistic number的位数:" << endl;
    cin >> i;
    cout << i << "位数的Narcissistic number包括:" << endl;
    for (n1 = pow(10, i - 1); n1 < pow(10, i); n1++)
    {
        n2 = 0;
        for (int j=0; j < i; j++)
        {
            a = pow(10, j);
            a = n1 / a;
            a = a % 10;
            a = pow(a, i);
            n2 = n2 + a;
        }
        if (n1 == n2)
            cout << n1 << endl;
    }
    return 0;
}

c版

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int cube(const int n){
    return n*n*n;
}
bool
isNarcissistic(const int n){//判断是不是水仙花数
    int hundreds=n/100;
    int tens=n/10-hundreds*10;
    int ones=n%10;
    return cube(hundreds)+cube(tens)+cube(ones)==n;
}
int main(void){
    int i;
    for(i=100;i<1000;++i){
        if(isNarcissistic(i))
        printf("%d\n",i);
    }
    return 0;
}

如有错误,欢迎评论!!!

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值