开发者

Method to determine is the square of a persons age == to the current year

I am trying to write a method that determines if the square of the age of a person is equal to the current year. For example a man was aged 43 in 1849 and the square of 43 is 1849. Below is my code for it but I dont know why my exception is not working because it is assumed that no body can live past 123 years

 public Boolean isAlive(int y){
     assert( y>=1888 && y<=2134);
     int age=0;
     while(age<=123){
         y=y+1;
         age=age+1;
 开发者_运维问答        if(age*age==y){
             int c=age;
             return true;
             }
         }
      return false;
   }


The problem you are trying to solve appears to be

y + n = n^2

where y is the starting year and n is the age and both must be a positive whole number.

Rearranged this is

n = (sqrt(1 + 4 * y) + 1)/2;

e.g.

when y = 1806, n = 43, n + y = n * n = 1849.

when y = 1980, n = 45, n + y = 2025, n * n = 2025.

So you can write

public boolean squareAgeIfBorn(int year) {
   double n = (Math.sqrt(1 + 4 * year) + 1) / 2;
   return Math.abs(n - (long) n) < 1e-9; // i.e. if n is a whole number.
}


You can make it much easier:

 public boolean isAlive(int age){
    int year = Calendar.getInstance().get(Calendar.YEAR);
    return year == age * age;   
 }


I don't catch your code but from description I think you want to check if square of someone's age is equal current year

  1. don't use assert
  2. count square of the age
  3. get current year
  4. compare if 2 == 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜