Topic: 有简单一点的求水仙花数的方法吗?? |
Print this page |
1.有简单一点的求水仙花数的方法吗?? | Copy to clipboard |
Posted by: Jasmin Posted on: 2006-01-08 18:48 除了以下这个方法外,还有简单一点的求水仙花数的方法吗??? import java.awt.*; import java.applet.*; import java.math.*; public class Shuixianhua extends Applet { public void init() { } public void paint(Graphics g) { //定义相关变量 int elem[]=new int[4]; int num,temp; double total; int row=20,column=30; int count=0,k; g.drawString("4位的水仙花数如下所示:", 20, 30 ); //利用循环寻找1000到10000之间的水仙花数 for(num=1000; num<10000; num++) { k=0; temp=num; //提取num中的千位,百位,十位,个位,存储在整型数组elem[4]中 do { elem[k]=temp%10; temp=temp/10; k++; }while(!(temp==0)); total=Math.pow(elem[0],4)+Math.pow(elem[1],4)+Math.pow(elem[2],4)+Math.pow(elem[3],4); //判断是否未水仙花数 if(total==num) { count++; //输出格式控制 if(count%8==0) { row=row+25; } else { column=column+30; } g.drawString(num+"是水仙花数",row,column); } column=column+30; g.drawString("共"+count+"个",row,column); } } |
2.Re:有简单一点的求水仙花数的方法吗?? [Re: Jasmin] | Copy to clipboard |
Posted by: lianfuye Posted on: 2006-01-11 17:11 看了半天楞是没看懂你的意识。 这是我的水仙花束: public class Sxhs{ public static void main(String[] agrs){ int a1 , a2 , a3; for(int i=1000 ; i<10000 ; i++){ a1 = i / 1000; a2=(i-a1*1000)/100; a3=i-a1*1000-a2*100; if(i==(a1*a1*a1)+(a2*a2*a2)+(a3*a3*a3)){ System.out.println("shi : " + i); } } } } |
3.Re:有简单一点的求水仙花数的方法吗?? [Re: Jasmin] | Copy to clipboard |
Posted by: awardwy Posted on: 2006-01-12 11:38 public class shuixianhua{ public static void main(String[] agrs){ int a1 , a2 , a3,a4; for(int i=1000 ; i<10000 ; i++){ a1 = i / 1000; a2=(i-a1*1000)/100; a3=(i-a1*1000-a2*100)/10; a4=i-a1*1000-a2*100-a3*10; if(i==(a1*a1*a1*a1)+(a2*a2*a2*a2)+(a3*a3*a3*a3)+(a4*a4*a4*a4)){ System.out.println("shi : " + i); System.out.println(a1); System.out.println(a2); System.out.println(a3); System.out.println(a4); } } } } |
4.Re:有简单一点的求水仙花数的方法吗?? [Re: Jasmin] | Copy to clipboard |
Posted by: cowskin Posted on: 2006-01-15 11:23 呵呵,小弟刚刚学了这个,这个是我老师写的程序,很牛哦~ public class Suixian { public static void main(String[] args) throws java.io.IOException { byte[] buf = new byte[20]; int cmdLength = System.in.read(buf); String str = new String(buf,0,cmdLength-2); int n = Integer.parseInt(str);//这里当然是输入一个位数罗,也不一定就三位吧 int low = 1,high = 1; for (int i=1;i<n;i++) low = low*10; high = low * 10; //System.out.println(low); //System.out.println(high); for (int i=low;i<high;i++) { int sum = 0; int p = i; while (p!=0) { int r = p%10; p = p/10; int rn = 1; for (int j=1;j<=n;j++) rn = rn * r; sum = sum + rn; } if (sum==i) System.out.println; } } } 不过这只是你程序的一个化简,(你的用了一个数组) 第二个方法是这样,拿三未数举例 public class SuiXian2 { public static void main(String[] args) { for (int a=1;a<=9;a++) for (int b=0;b<=9;b++) for (int c=0;c<=9;c++) if(a*a*a+b*b*b+c*c*c==100*a+10*b+c) System.out.println(100*a+10*b+c); } } 这是我上论坛来发的第一封贴子,望指教 |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |