这是我的代码,它不会产生任何输出。因为我从100开始循环所以根据使用的逻辑,我应该得到答案为153.但没有任何事情发生。请帮忙。
// Program to find the first Angstrom Number and display it!
public static void main(String[] args) {
int sum = 0;
int y, z;
System.out.println("Starting program");
for (int i = 100; i < 1000; i++) {
sum += (i % 10) * (i % 10) * (i % 10);
y = i / 10;
sum += (y % 10) * (y % 10) * (y % 10);
z = y / 10;
sum += z * z * z;
if (sum == i) {
System.out.println("The first Angstrom number is " + i);
break;
}
}
}
答案 0 :(得分:2)
您应该在每个步骤中重置总和:
for (int i = 100; i < 1000; i++) {
sum = 0;
sum += (i%10) * (i%10) * (i%10);
....
}
答案 1 :(得分:0)
使用此逻辑,您可以在两个数字之间找到阿姆斯壮数字。只需根据需要更改值即可。
public class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
}
该程序的输出为:
1634 8208 9474 54748 92727 93084
答案 2 :(得分:0)
public static int Power(int out,int res)
{
int count=res;
int temp=1;
while(count!=0)
{
temp=temp*out;
count--;
}
return temp;
}
public static int count1(int num)
{
int count=0;
while(num!=0)
{
num=num/10;
count++;
}
return count;
}
public static int isArmstrong(int num)
{
int out;
int sum=0;
int res=count1(num);
while(num!=0)
{
out=num%10;
sum=sum+Power(out,res);
num=num/10;
}
return sum;
}
public static void main(String[] args)
{
int start=10;
int end=100000;
for(int i=start;i<=end;i++)
{
int result=isArmstrong(i);
if(result==i)
{
System.out.println(i);
}