阿姆斯特朗数是数学中的一个概念,多用于计算机语言编程。
基本介绍
如果一个n位正整数等于其各位数字的n次方之和,则称该数为阿姆斯特朗数。
例如1^3 + 5^3 + 3^3 = 153
当n=3时,又称水仙花数,特指一种三位数,其各个数之立方和等于该数。
水仙花数共有4个,分别为:153、370、371、407。
1000以内的
1000以内的阿姆斯特朗数
1,153,370,371,407
Python实例
number = 0
i = 1
while number \u003c 1000 :
number = number +1
b = i//100 # 对一个数取百位数
c = i//10%10 # 对一个数取十位数
d = i%10 # 对一个数取个位数
if i == 0 :
print(i)
i = i + 1
elif (i == b*b*b+c*c*c+d*d*d):
print(i)
i = i + 1
else :
i = i + 1
c语言实例
如果一个正整数等于其各个数字的n次方和,则称该数为亨利·爱德华·阿姆斯特朗数(亦称为自恋性数)。
如 407=64+0+343就是一个阿姆斯特朗数。试编程求1000以内的所有阿姆斯特朗数。
*问题分析与算法设计
可采用穷举法,依次取1000以内的各数(设为i),将i的各位数字分解后,据阿姆斯特朗数的性质进行计算和判断。
*程序说明与注释
#include\u003cstdio.h\u003e
int main()
{
int i,t,k,a;
printf("There are follwing armstrong number smaller than 1000:\n");
for(i=2;i\u003c1000;i++) /*穷举要判定的数i的取值范围2~1000*/
{
for(t=0,k=1000;k\u003e=10;t++) /*截取整数i的各位(从高向低位)*/
{
a[t]=(i%k)/(k/10); /*分别赋于a~a[2}*/
k/=10;
if(a*a*a+a*a*a+a*a*a==i)
/*判断i是否为阿姆斯特朗数*/
printf("%5d",i); /*若满足条件,则输出*/
}
}
return 1;
}
*运行结果
There are following armstrong number smaller than 1000:
153 370 371 407
C++实例
本程序为1000000000以内的阿姆斯特朗数
以下程序是错的。
#include "stdafx.h"
#define Cube(x) x*x*x
int totalCount(int);
int _tmain(int argc, _TCHAR* argv[])
{
int cnt=0;
int n=0;
scanf("%d",\u0026n);
cnt=totalCount(n);
printf("\n%d\n",cnt);
return 0;
}
int totalCount(int num)
{
if(num\u003c2)
return 0;
int count=0;
int ii=0;
int temp;
int sum=0;
int temp2=0;
for(ii=2 ;ii\u003c=num;ii++)
{
sum=0;
temp2=ii;
while(temp2\u003e0)
{
temp=temp2%10;
temp2=temp2/10;
sum+=Cube(temp);
}
if(sum==ii)
{
printf("%d\t",ii);
count++;
}
}
return count;
}
C#实例
以下才是1000000000以内的阿姆斯特朗数
private void btnSearch_Click(object sender, EventArgs e)
{
int i = 101;
int j = 1;
while ((long)i \u003c 1000000000)
{
if (i \u003c 数学Pow(10,(j+2)))
{
if ((int)Getresult(i, j) == i)
{
txtResult.Text += i.ToString() + Environment.NewLine;
}
}
else
{
j++;
}
i++;
}
}
private static int Getresult(int i, int j)
{
int result = 0;
for (int x = 0; x \u003c i.ToString().Length; x++)
{
int te = Convert.ToInt32(i.ToString().Substring(x, 1));
result+=(int)(数学Pow(te, (j + 2)));
}
return result;
}
Java实例
public class Test {
public static void main(String[] args) {
for (int x = 1; x \u003c 10; x++) {
for (int y = 0; y \u003c 10; y++) {
for (int z = 0; z \u003c 10; z++) {
if (x*x*x+y*y*y+z*z*z==x*100+y*10+z) {
System.out.println(x*100+y*10+z);
}
}
}
}
}
}
求num以内的所有数
var num = 999999999;
for (var i = 100; i \u003c= num i++)
{
var s = i.toString();
var count = 0;
for (var j = 0; j \u003c s.length; j++) count += 数学pow(parseInt(s[j]), s.length);
if (count == i) {
console.log("find number:" + i);
}
}