# Determine the Last Digits of N^2 == N in Java

## The challenge

Let’s call an integer number `N` ‘green’ if `N²` ends with all of the digits of `N`. Some examples:

`5` is green, because `5² = 25` and `25` ends with `5`.

`11` is not green, because `11² = 121` and `121` does not end with `11`.

`376` is green, because `376² = 141376` and `141376` ends with `376`.

Your task is to write a function `green` that returns `n`th green number, starting with `1` – `green (1) == 1`

### Data range

`n <= 500`0

## The solution in Java code

```.wp-block-code{border:0;padding:0}.wp-block-code>div{overflow:auto}.shcb-language{border:0;clip:rect(1px,1px,1px,1px);-webkit-clip-path:inset(50%);clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal;word-break:normal}.hljs{box-sizing:border-box}.hljs.shcb-code-table{display:table;width:100%}.hljs.shcb-code-table>.shcb-loc{color:inherit;display:table-row;width:100%}.hljs.shcb-code-table .shcb-loc>span{display:table-cell}.wp-block-code code.hljs:not(.shcb-wrap-lines){white-space:pre}.wp-block-code code.hljs.shcb-wrap-lines{white-space:pre-wrap}.hljs.shcb-line-numbers{border-spacing:0;counter-reset:line}.hljs.shcb-line-numbers>.shcb-loc{counter-increment:line}.hljs.shcb-line-numbers .shcb-loc>span{padding-left:.75em}.hljs.shcb-line-numbers .shcb-loc::before{border-right:1px solid #ddd;content:counter(line);display:table-cell;padding:0 .75em;text-align:right;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;white-space:nowrap;width:1%}```import java.math.BigInteger;
import java.util.TreeSet;

public class GreenNumbers {
public static BigInteger get(int n) {
if (n == 1) {
return BigInteger.ONE;
}

TreeSet<BigInteger> treeSet = new TreeSet<>();
addNumber(treeSet, n + n / 5);
BigInteger[] bigIntegers = treeSet.toArray(new BigInteger[]{});
return bigIntegers[n - 2];
}

public static void addNumber(TreeSet<BigInteger> treeSet, int number) {
int digitNo = 2;
int counter = 2;
BigInteger num = new BigInteger("5");
BigInteger num2 = new BigInteger("6");
while (counter < number) {
BigInteger numSquared = num.multiply(num);
BigInteger powOfTen = new BigInteger("10").pow(digitNo);
num = numSquared.mod(powOfTen);
counter += 2;
digitNo++;
}
}
}
```Code language: Java (java)```

## Test cases to validate our solution

``````import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;
import java.math.BigInteger;

public class SolutionTest {
@Test
public void basicTests() {
assertEquals(new BigInteger("1"),  GreenNumbers.get(1));
assertEquals(new BigInteger("5"),  GreenNumbers.get(2));
assertEquals(new BigInteger("6"),  GreenNumbers.get(3));
assertEquals(new BigInteger("25"), GreenNumbers.get(4));
}

@Test
public void biggerTests() {
assertEquals(new BigInteger("2890625"), GreenNumbers.get(12));
assertEquals(new BigInteger("7109376"), GreenNumbers.get(13));
}

@Test