【问题标题】:Algorithm for multiplying arbitrary length polynomials?乘以任意长度多项式的算法?
【发布时间】:2014-09-20 00:52:01
【问题描述】:

假设我们将多项式表示为一个浮点数组,其中多项式中每个项目的度数对应于数组中的索引(例如,4.2x^5+x^2-1.4 将表示为{-1.4, 0, 1, 0, 0, 4.2}

我的作业问题是用 C 语言编写一个方法,将两个任意长度的多项式相乘并打印出结果(而不是返回结果)。

通常,当我问关于 SO 的问题时,我会包括我迄今为止尝试过的内容,但我真的对这个完全一无所知。这就是我所拥有的:

void multpoly(float *a, int len_a, float *b, int len_b)
{
    for(i = 0; i < len_result; i++)
    {
        printf(" %.5f, ", product[i]);
    }
}

任何帮助将不胜感激!

【问题讨论】:

  • 手工计算并发布结果:(ax^2 + bx + c) * (dx^5 + ex^2 + f).
  • @user3386109 什么?它与问题有何联系?
  • @python 嗯,让我们看看,标题是“乘以任意长度的多项式”。 认为这意味着什么?
  • 你的表述不正确,应该是{-1.4, 0, 1, 0, 0, 4.2}
  • @user3386109 - 谢谢,确实有帮助!我现在可以更轻松地看到“一般情况”之类的东西

标签: c polynomial-math


【解决方案1】:

我相信这是你想要的:

// constraints: 'result' must have space for at least len1 + len2 - 1 elements.
void multpoly(const float *poly1, int len1, const float *poly2, int len2, float *result)
{
    int i, p1i, p2i;
    int len_result = len1 + len2 - 1;

    for (i = 0; i < len_result; i++) result[i] = 0.0;

    for (p1i = 0; p1i < len1; ++p1i)
        for (p2i = 0; p2i < len2; ++p2i)
            result[p1i + p2i] += poly1[p1i] * poly2[p2i];
}

Ideone example of this function

【讨论】:

  • 是的,这行得通,但有人比你快;)
  • Stackoverflow 不是一场竞赛。
  • 你是对的,但是添加相同的答案有什么意义!我的意思是它已经在那里了!!无论如何,请编辑您的答案,因为我看不到您的代码应该在哪里prints out the result (rather than returning it).
【解决方案2】:
#include <stdio.h>
#include <string.h>

main()
{
    float a[5]={1, 2, 3};
    float b[5]={2, 0, 1};

    printPol(a, b, 3, 3);

}

void printPol(float*a, float*b, int len1, int len2)
{
    int i, j;

    // order of resulting poly is o1+o2
    // o1 = len1 -1
    // o2 = len2 -1
    // length is order + 1 (+1 is the constant number)
    int len = (len1-1)+(len2-1)+1;

    float res[len];
    //initialize 
    for(i=0;i<len; i++) res[i] = 0;


    for(i=0; i<len1; i++)     
        for(j=0; j<len2; j++)
        {
            // mutually multiply all elements

            res[i+j] += a[i]*b[j]; 
        }
    printf("%f ", res[0]);  
    for(i=1;i<len; i++) printf("+%f*x^%d ", res[i], i);


}

【讨论】:

  • "得到的 poly 的顺序是 o1*o2" 不,显然不是。
猜你喜欢
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
相关资源
最近更新 更多