說明
在三位的整數中,例如153可以滿足13 + 53 + 33 = 153,這樣的數稱之為Armstrong數,試寫出一程式找出所有的三位數Armstrong數。
解法
Armstrong數的尋找,其實就是在問如何將一個數字分解為個位數、十位數、百位數......,這只要使用除法與餘數運算就可以了,例如輸入 input為abc,則:
a = input / 100
b = (input%100) / 10
c = input % 10
#include <stdio.h>
int main(void) { int input; for(input = 100; input <= 999; input++) { int a = input / 100; int b = (input % 100) / 10; int c = input % 10; if(a*a*a + b*b*b + c*c*c == input) printf("%d ", input); } return 0; }
public class Armstrong { public static void main(String[] args) { for(int i = 100; i <= 999; i++) { if(Math.pow(i/100, 3) + Math.pow((i%100)/10, 3) + Math.pow(i%10, 3) == i) System.out.print(i + " "); } } }
print([i for i in range(100, 1000) if (i // 100) ** 3 + ((i % 100) // 10) ** 3 + (i % 10) ** 3 == i])
(for( i <- 100 to 999; a = i / 100; b = (i % 100) / 10; c = i % 10; if a*a*a + b*b*b + c*c*c == i ) yield i) foreach(n => print(n + " "))
class Range def comprehend(&block) return self if block.nil? self.collect(&block).compact end end
p (100..999).comprehend { |i| i if (i / 100) ** 3 + ((i % 100) / 10) ** 3 + (i % 10) ** 3 == i }
|