求水仙花数合集:
PHP实现:
<?php //使用系统自带函数,即可实现幂运算,何必画蛇添足,自己写函数 functionis_narcissistic($n) { $hundreds=floor($n/100);//分解出百位 $tens=floor($n/10)%10;//分解出十位 $ones=floor($n%10);//分解出个位 return(bool)(pow($hundreds,3)+pow($tens,3)+pow($ones,3)==$n); } for($i=100;$i<1000;++$i) { if(is_narcissistic($i)) echo$i."\n"; } die(); ?>
Visual Basic 的“水仙花数”实现代码:
PrivateSubCommand1_Click() DimiAsInteger,aAsInteger,bAsInteger,cAsInteger Fori=100To999Step1 a=i\100 b=(i-100*a)\10 c=i-100*a-10*b Ifa^3+b^3+c^3=iThen Printi EndIf Nexti EndSub
c语言实现:
#include <stdio.h> #include <stdlib.h> void main() { int i,j,k,n; printf("'water flower'number is:"); for(n=100;n<10000;n++) { i=n/100;/*分解出百位*/ j=n/10%10;/*分解出十位*/ k=n%10;/*分解出个位*/ if(n==i*i*i+j*j*j+k*k*k) { printf("%-5d",n); } } printf("\n");
Java 实现:
package sy1; import java.util.Scanner; public class TestNarcissus { /* * public static void main(String[] args) { * int num = 100; int a[] = new int[3]; * System.out.print("3位的水仙花数有:\t"); * while (num <= 999) { * int sum =0; * a[0] = num / 100 % 10; * a[1] = num / 10 % 10; * a[2] = num % 10; * for (int i = 0; i < 3; i++) { * sum = sum + (int) Math.pow(a[i], 3); * } * if (num ==sum) { * System.out.print(num + "\t"); } num++; * } * } */ public static void main(String[] agrs) { System.out.print("Input N:"); Scanner input = new Scanner(System.in); int N = input.nextInt(); for (int i = 3; i <= N; i++) { int a[] = new int[N]; int num = (int) Math.pow(10, i - 1) + 1; System.out.print(i + "位的水仙花数有:\t"); while (num <= Math.pow(10, i)) { int sum = 0; for (int j = 0; j < i; j++) a[j] = (int) (num / Math.pow(10, j) % 10); for (int j = 0; j < i; j++) { sum = sum + (int) Math.pow(a[j], i); } if (num == sum) { System.out.print(num + "\t"); } num++; } System.out.print("\n"); } } }
C# asp.net 实现
for(inti=100;i<1000;i++) { intbai=0;intshi=0;intge=0;intbaiyushu=0; bai=i/100; baiyushu=i%100; shi=baiyushu/10; ge=baiyushu%10; if(i==bai*bai*bai+shi*shi*shi+ge*ge*ge) {Console.WriteLine("水仙花数:"+i+" ");} }
C 版权标识:[ R ] ←这是什么?什么是版权标识?点我解释~
原文参考链接:百度百科-水仙花数