std::ratio power of a std::ratio at compile-time?

前端 未结 2 1430
再見小時候
再見小時候 2021-02-06 09:10

I have a challenging question from a mathematical, algorithmic and metaprogramming recursion point of view. Consider the following declaration:

template

        
2条回答
  •  情歌与酒
    2021-02-06 09:30

    Yes, it's possible.

    Let's define R1 = P1/Q1, R2 = P2/Q2, and R1^R2 = R3 = P3/Q3. Assume further that P and Q are co-primes.

    R1^R2 = R1^(P2/Q2) = R3
    R1 ^ P2 = R3 ^ Q2.
    

    R1^P2 is known and has a unique factoring into primes 2^a * 3^b * 5^c * ... Note that a, b, c can be negative as R1 is P1/Q1. Now the first question is whether all of a,b,c are multiples of known factor Q2. If not, then you fail directly. If they are, then R3 = 2^(a/Q2) * 3^(b/Q2) * 5^(c/Q2) ....

    All divisions are either exact or the result does not exist, so we can use pure integer math in our templates. Factoring a number is fairly straightforward in templates (partial specialization on x%y==0).

    Example: 2^(1/2) = R3 -> a=1, b=0, c=0, ... and a%2 != 0 -> impossible. (1/9)^(1/2) -> a=0, b=-2, b%2 = 0, possible, result = 3^(-2/2).

提交回复
热议问题