Java prints out the implementation code for all daffodils

  • 2020-06-12 09:03:18
  • OfStack

Title: Print out all "daffodils". A "daffodils" is a three-digit number whose cube sum equals the number itself. For example, 153 is a number of daffodils because 153=1 to the third +5 to the third +3 to the third.

Program analysis: for cycle was used to control 100-999 Numbers, and each number was decomposed into the ones, 10 and hundreds digits.

Program design:


public class exp2{
  public static void main(String args[]){
    int i=0;
    math mymath = new math();
    for(i=100;i<=999;i++)
      if(mymath.shuixianhua(i)==true)
      System.out.println(i);
  }
}
class math
{
  public int f(int x)
  {
    if(x==1 || x==2)
      return 1;
    else
      return f(x-1)+f(x-2);
  }
  public boolean iszhishu(int x)
  {
    for(int i=2;i<=x/2;i++)
      if (x % 2==0 )
       return false;
    return true;
  }
  public boolean shuixianhua(int x)
  {
    int i=0,j=0,k=0;
    i=x / 100;
    j=(x % 100) /10;
    k=x % 10;
    if(x==i*i*i+j*j*j+k*k*k)
     return true;
    else
     return false;
   
  }
}

For more, please pay attention to previous posts on this site.


Related articles: