现在的位置: 首页 > 综合 > 正文

计算水仙花数

2014年02月26日 ⁄ 综合 ⁄ 共 1253字 ⁄ 字号 评论关闭

//数据结果课 老师布置了计算水仙花数程序转载如下:

package com.WildCat.Shuixianhuan;
import java.math.BigInteger;
import java.util.Arrays;
public class a {
  private static BigInteger[] table = new BigInteger[10];

  public static void main(String[] args) {
	  long time = System.nanoTime();
	  find(21);//计算21位水仙花数
	  time = System.nanoTime() - time;
	  System.out.println(time/1000000000.0 + "s");
  }

  public static void find(int n) {
  for (int i = 0; i < 10; i++)
	  table[i] = BigInteger.valueOf(i).pow(n);
  int[] nums = new int[n];
  int index = 0;
  int num = 0;
  while (true) {
	  if (index < nums.length && num < 10) {
	  nums[index] = num;
	  index++;
	  continue;
      } else if (index >= nums.length) {
	  BigInteger big = sum(nums);
	  int[] temp = getArray(big);
	  if (check(nums, true, temp, false))
	  System.out.println(big);
	  } else if (index <= 0) {
	  break;
      }
	  index--;
	  num = nums[index] + 1;
	  }
  }
//判断两个大整数是否相等
  public static boolean check(int[] a1, boolean copy1, int[] a2, boolean copy2) {
	  if (a1.length != a2.length)
	  return false;
	  if (copy1)
	    a1 = a1.clone();
	  if (copy2)
	    a2 = a2.clone();
	  Arrays.sort(a1);
	  Arrays.sort(a2);
	  return Arrays.equals(a1, a2);
  }
//求和函数
  public static BigInteger sum(int[] nums) {
	  BigInteger sum = BigInteger.ZERO;
	  for (int i = 0; i < nums.length; i++)
	  sum = sum.add(table[nums[i]]);
	  return sum;
  }
  //把大整数变成数组
  public static int[] getArray(BigInteger big) {
	  String s = String.valueOf(big);
	  int length = s.length();
	  int[] res = new int[length];
	  for (int i = 0; i < length; i++)
	  res[i] = s.charAt(i) - '0';
	  return res;
  }
}

抱歉!评论已关闭.