JAVA-水仙花數


7-1 JAVA-水仙花數 (14 分)
水仙花數是指一個N位正整數(7≥N≥3),它的每個位上的數字的N次冪之和等於它本身。例如:153=13+53+33。 要求編寫程序,計算所有N位水仙花數。

輸入格式:
輸入一個正整數N(3≤N≤7)。

輸出格式:
按遞增順序輸出所有N位水仙花數,每個數字占一行。

輸入樣例:
在這里給出一組輸入。例如:

3
輸出樣例:
在這里給出相應的輸出。例如:

153
370
371
407

import java.util.Scanner;
import static java.lang.Math.*;
//方法一 該方法會導致運行超時,不建議使用,初學者實力有限目前沒辦法解決,歡迎大神來評論區交流
public class test1 {
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        int N=sc.nextInt();
        sc.close(); //關閉Scanner對象
        int num[]=new int[N];
        int a=(int) pow(10,N-1);
        int b=(int) pow(10,N);
        for(int i = a; i<b; i++)
        {
            int sum=0;
            for(int j=0;j<N;j++)
            {
                num[j]=(int)(i/pow(10,j)%10);
                sum+=(int)pow(num[j],N);
            }
            if(sum==i)
                System.out.println(i);
        }
    }
}

//方法二
import java.util.Scanner;
import static java.lang.Math.pow;

public class test2 {
  public static void main(String[] args)
  {
      Scanner sc=new Scanner(System.in); 
      int N=sc.nextInt(); 
      sc.close();  //關閉Scanner對象
      int num[]=new int[N];
      int a=(int) pow(10,N-1);
      int b=(int) pow(10,N);
      for(int i = a; i<b; i++)
      {
          int l=i;
          int sum=0;
          for(int j=0;j<N;j++)
          {
              int c=1;
              for (int k = 0; k < N; k++) //遍歷n位數
              {
                  c=c*(l%10);  //計算某位數的n次方
              }
              sum+=c;
              l=l/10;
          }
          if(sum==i)
              System.out.println(i);
      }
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM