DEV Community

Acid Coder
Acid Coder

Posted on

Typescript Numeric Literal Types How To Find Nth Root of X

In this post we are going to try to find nth root of x

where x and n are both numeric literal types

to do this, we need to utilize exponentiation type with a slight modification:

type CreateArrayWithLengthX< LENGTH extends number, ACC extends unknown[] = [], > = ACC['length'] extends LENGTH ? ACC : CreateArrayWithLengthX<LENGTH, [...ACC,1]> type Multiplication<X extends number, Y extends number, Z extends number[] = [], V extends unknown[] = []> = [...CreateArrayWithLengthX<Y>]['length'] extends Z['length'] ? V : Multiplication<X,Y,[1,...Z],[...CreateArrayWithLengthX<X>,...V]> type Exponentiation<X extends number, N extends number, Counter extends number[] =[], Acc extends unknown[] = [1]> = Counter['length'] extends N ? Acc // modified  : Exponentiation<X, N, [1, ...Counter], Multiplication<Acc['length'],X> > 
Enter fullscreen mode Exit fullscreen mode

ok, we have the building block now, let's do it

type Root <X extends number, N extends number, Counter extends number[] = []> = [...Exponentiation<Counter['length'], N>]['length'] extends X ? Counter['length'] : Root<X, N, [1,...Counter]> type A = Root<4,2> // 2 type B = Root<8,3> // 2 type C = Root<81,4> // 3 type D = Root<625,4> // 5 type E = Root<1024,10> // 2 type F = Root<2187,7> // 3 type G = Root<9261,3> // 21 
Enter fullscreen mode Exit fullscreen mode

playground

limitation: X and N must be positive integers and only works with positive integer root. X cannot exceed 9,999 because the max tuple size is 9,999

X can exceed 999 if result^(N-1) is less than 1000

Warning, please insert the input one by one or else it will break the playground.

Top comments (0)