阿姆斯特朗數

阿姆斯特朗數是數學中的一個概念,多用於計算機語言編程。

基本介紹

  • 中文名:阿姆斯特朗數
  • 學科:數學,計算機
  • 適用領域:計算機語言編程
  • >億的數:153 370 371 407
  • 定義:一n位正整數=各位數字n次方之和
  • 分析方法窮舉法
基本介紹,1000以內的,

基本介紹

如果一個n位正整數等於其各位數字的n次方之和,則稱該數為阿姆斯特朗數。
例如1^3 + 5^3 + 3^3 = 153
當n=3時,又稱水仙花數,特指一種三位數,其各個數之立方和等於該數。
水仙花數共有4個,分別為:153、370、371、407。

1000以內的

1000以內的阿姆斯特朗數
1,2, 3, 4, 5, 6, 7, 8, 9,153,370,371,407
Python程式語言實例
number = 0
i = 1
while number < 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<stdio.h>
int main()
{
int i,t,k,a[3];
printf("There are follwing armstrong number smaller than 1000:\n");
for(i=2;i<1000;i++) /*窮舉要判定的數i的取值範圍2~1000*/
{
for(t=0,k=1000;k>=10;t++) /*截取整數i的各位(從高向低位)*/
{
a[t]=(i%k)/(k/10); /*分別賦於a[0]~a[2}*/
k/=10;
if(a[0]*a[0]*a[0]+a[1]*a[1]*a[1]+a[2]*a[2]*a[2]==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",&n);
cnt=totalCount(n);
printf("\n%d\n",cnt);
return 0;
}
int totalCount(int num)
{
if(num<2)
return 0;
int count=0;
int ii=0;
int temp;
int sum=0;
int temp2=0;
for(ii=2 ;ii<=num;ii++)
{
sum=0;
temp2=ii;
while(temp2>0)
{
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 < 1000000000)
{
if (i < Math.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 < i.ToString().Length; x++)
{
int te = Convert.ToInt32(i.ToString().Substring(x, 1));
result+=(int)(Math.Pow(te, (j + 2)));
}
return result;
}
Java實例
public class Test {
public static void main(String[] args) {
for (int x = 1; x < 10; x++) {
for (int y = 0; y < 10; y++) {
for (int z = 0; z < 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);
}
}
}
}
}
}
JavaScript實例
求num以內的所有數
var num = 999999999;
for (var i = 100; i <= num i++)
{
var s = i.toString();
var count = 0;
for (var j = 0; j < s.length; j++) count += Math.pow(parseInt(s[j]), s.length);
if (count == i) {
console.log("find number:" + i);
}
}

相關詞條

熱門詞條

聯絡我們