다항식(polynomial)은 문자의 거듭제곱의 상수 배들의 합을 표현하는 수식이다. 예를 들어 x^2+2x+3 같은 식을 의미한다. 그중 변수가 하나인 것을 일변수 다항식이라고 하고 이는 다음과 같이 표현한다.

f(x) = ax^n + bx^(n-1)+...+cx+d

최대 일차 일변수 다항식이 주어졌을 때 그 함수를 적분한 결과를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 최대 일차 일변수 다항식이 주어진다. 항의 개수는 최대 2개이고, 변수는 항상 x로 주어지며, 각 항은 공백 문자로 구분되지 않는다. 주어지는 계수는 절댓값이 10,000을 넘지 않는 0이 아닌 2의 배수이고 주어지는 상수는 절댓값이 10,000을 넘지 않는 정수이다. 차수가 같은 항은 한 번만 주어진다. 단, 계수의 절댓값이 1인 경우에는 1을 생략한다. 다항식은 차수가 큰 것부터 작아지는 순서대로 주어진다.

출력

주어진 일변수 다항식을 적분한 결과를 입력 형식과 동일하게 출력한다. 적분상수는 "W"로 x^2은 "xx"로 표현한다.

예제 입력 1

6x+6

예제 출력 1

3xx+6x+W

힌트

문제에서 다루는 적분법은

 을 사용한다. (W는 적분상수) 또한 적분 가능 함수에 대하여 합의 법칙,

 가 성립한다.


더보기

Solution

#include<stdio.h>
#include<string.h>

int main(void)
{
	char calculation[20]={'\0', };
	int variable=0, constant=0, index=0, minus[2]={1,1};

	fgets(calculation,sizeof(calculation),stdin);

	if(strlen(calculation)>1)
	{
		if(calculation[index]=='-')
		{
			minus[0]=-1;
			index++;
		}
		while(index<strlen(calculation) && calculation[index]!='x')
		{
			variable*=10;
			variable+=calculation[index++]-'0';
		}
		if(index<strlen(calculation) && calculation[index]=='x')
			index++;
		else
		{
			minus[1]=minus[0];
			minus[0]=1;
			variable-=calculation[index-1]-'0';
			variable/=10;
			constant=variable;
			variable=0;
		}
		if(index<strlen(calculation))
		{
			if(calculation[index]=='-')
				minus[1]=-1;
			index++;
		}
		while(index<strlen(calculation) && calculation[index]>='0' && calculation[index]<='9')
		{
			constant*=10;
			constant+=calculation[index++]-'0';
		}

		variable*=minus[0];
		switch(variable)
		{
			default:
				if(variable==-2)
					printf("-");
				else
					printf("%d", variable/2);
			case 2:
				printf("xx");
				if(minus[1]==1)
					printf("+");
			case 0:
				if(minus[1]==-1)
					printf("-");
				break;
		}
		switch(constant)
		{
			default:
				printf("%d", constant);
			case 1:
				printf("x+");
			case 0:
				break;
		}
	}
	printf("W\n");

	return 0;
}
728x90

+ Recent posts