# [J], 40 bytes

    ((2|+/~)@]+2**@[*=/~@]*(>:]*=/~))|@i:@<:

[Try it online!][TIO-kvffs36t]

[J]: http://jsoftware.com/
[TIO-kvffs36t]: https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTSMarT16zQdYrWNtLQcorVs9escYrU07KxiQUxNzRqHTCsHG6v/mlypyRn5QJ1pCkYQprqurq46hGkIFDXGEDUCipr8BwA "J – Try It Online"