持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
小E最近在学习求导,他给了你一个多项式,让你帮忙求出它的导数。
形式化地说,不妨假设 xi 项数的系数为 A,规定一个多项式的正确的表达方式如下:
- 各项次数非负且递减。
- 如果 A=0,不写出这一项,否则如果 A=1,且 i=0,不写出系数。
- 对于 i=0 的项,表示成
A;对于 i=1 的项,表示成Ax;对于其他项,表示成Ax^i。 - 如果该项是负的,要在前面加上负号,否则加正号。注意,如果该项是正的且为第一项,则正号和负号都不用加。
- 特别地,如果多项式为f(x)=0,它应该被表示成
f(x)=0。
输入格式:
首先输入 f(x)= ,之后给出多项式,例如 x ^ 4−3x ^ 2−x+1,格式与题目描述中的一致。
数据保证输入的字符串长度不超过 106,输入多项式的系数和次数均不超过 105。
输出格式:
首先输出 f'(x)=,之后输出所给多项式的导数,格式与题目描述中的一致。
请注意其中 f'(x) 的 ' 在输出时应该输出英文符号。
输入样例:
f(x)=x^4-3x^2-x+1
输出样例:
f'(x)=4x^3-6x-1
首先已知f(x)=0的时候是不变的
其次阶数在不断递减,所以我们可以找出最后一个含‘^’的位置,在他之后全部都是0,不需要改变然后特别判断第一位,看他是+还是-,在每几个判断一下例如2x^3这种,最后在注意一下细节就可以了
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
void solve()
{
string s;
cin >> s;
if(s == "f(x)=0")
{
cout << "f(x)=0" << '\n';
return ;
}
int l = 0,r = 0;
for(int i = 5;i < int(s.size()); i ++)
{
if(s[i] == 'x')
l ++;
if(s[i] == '^')
r ++;
}
if(l == 0)
{
cout << "f'(x)=0" << '\n';
return ;
}
string s1;
for(int i = 5;i < int(s.size());i ++)
{
s1+=s[i];
if(s[i] == 'x')
l--;
if(l == 0&&(s[i+1] == '+'|| s[i+1] == '-'))
break;
}
cout << "f'(x)=";
int cnt = 0;
if(s1[0] == '-')
cout << '-',cnt = 1;
int res = 0;
int num = 0;
vector<string>ans;
for(int i = cnt;i <int(s1.size());i ++)
{
while(s1[i] >='0' && s1[i] <= '9')
{
int x = s1[i] - '0';
res = res*10 + x;
i++;
if(i == int(s1.size()))
{
break;
}
}
if(i == int(s1.size()))
{
ans.push_back("0");
return ;
}
if(s1[i] == 'x')
{
num = res,res = 0;
if(i - 1 >= 0)
{
if(s1[i-1] < '0' || s1[i-1] > '9')
num = 1;
}
else
num = 1;
//cout << num << " "<< res <<'\n';
if(s1[i+1] == '^')
{
i += 2;
if(s1[i] <'0' || s1[i] > '9')
{
string z = to_string(num);
ans.push_back(z);
}
else
{
while(s1[i] >='0' && s1[i] <= '9')
{
int x = s1[i] - '0';
res = res*10 + x;
i++;
if(i == int(s1.size()))
break;
}
//cout << "num" << num << " " << res << '\n';
string z = to_string(1LL*res*num);
ans.push_back(z);
ans.push_back("x");
if(res > 2)
{
ans.push_back("^");
res --;
string w = to_string(res);
ans.push_back(w);
}
}
}
else
{
string z = to_string(num);
ans.push_back(z);
}num = 0,res = 0;
}
if(s1[i] == '+' || s1[i] == '-')
{
//cout << i << '\n';
if(s1[i] == '+')
{
string z = "+";
ans.push_back(z);
}
else
{
string z = "-";
ans.push_back(z);
}
}
}
for(int i = 0;i < int(ans.size());i ++)
cout << ans[i];
cout << '\n';
}
int main()
{
solve();
}