Using Prolog to compute the GCD of a polynomial

后端 未结 1 1389
情话喂你
情话喂你 2021-01-27 04:37

The title kind of says it all. I\'m looking to compute the GCD of two polynomials. Is there any way this can be done in Prolog? If so, what\'s a good starting point? Specificall

相关标签:
1条回答
  • 2021-01-27 04:55

    This answer is meant as a push in the right direction.

    First, forget for a moment that you need to parse an expression like x^2 + 7x + 6; this isn't even a proper term in Prolog yet. If you tried to write it on the top level, you will get an error:

    ?- Expr = x^2 + 7x + 6.
    ERROR: Syntax error: Operator expected
    ERROR: Expr = x^2 + 
    ERROR: ** here **
    ERROR: 7x + 6 . 
    

    Prolog doesn't know how to deal with the 7x you have there. Parsing the expression is a question of its own, and maybe it is easier if you assumed you have already parsed it and gotten a representation that looks for example like this:

    [6, 7, 1]
    

    Similarly, x^2 − 5x − 6 becomes:

    [-6, -5, 1]
    

    and to represent 0 you would use the empty list:

    []
    

    Now, take a look at the algorithm at the Wikipedia page. It uses deg for the degree and lc for the leading coefficient. With the list representation above, you can define those as:

    The degree is one less then the length of the list holding the coefficients.

    poly_deg(F, D) :-
        length(F, N),
        D is N - 1.
    

    The leading coefficient is the last element of the list.

    poly_lc(F, C) :-
        last(F, C).
    

    You also need to be able to do simple arithmetic with polynomials. Using the definitions on the Wikipedia page, we see that for example adding [] and [1] should give you [1], multiplying [-2, 2] with [1, -3, 1] should give you [-2, 8, -8, 2]. A precursory search gave me this question here on Stackoverflow. Using the predicates defined there:

    ?- poly_prod([-2,2], [1, -3, 1], P).
    P = [-2.0, 8.0, -8.0, 2] .
    
    ?- poly_sum([], [1], S).
    S = [1].
    

    From here on, it should be possible for you to try and implement polynomial division as outlined in the Wiki article I linked above. If you get into more trouble, you should edit your question or ask a new one.

    0 讨论(0)
提交回复
热议问题