B. Ternary Logic

来源:互联网 发布:怎么下载淘宝搜索量 编辑:程序博客网 时间:2024/05/21 01:57

time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Little Petya very much likes computers. Recently he has received a new "Ternatron IV" as a gift from his mother. Unlike other modern computers, "Ternatron IV" operates with ternary and not binary logic. Petya immediately wondered how the xoroperation is performed on this computer (and whether there is anything like it).

It turned out that the operation does exist (however, it is called tor) and it works like this. Suppose that we need to calculate the value of the expression a tor b. Both numbers a and b are written in the ternary notation one under the other one (bunder a). If they have a different number of digits, then leading zeroes are added to the shorter number until the lengths are the same. Then the numbers are summed together digit by digit. The result of summing each two digits is calculated modulo 3. Note that there is no carry between digits (i. e. during this operation the digits aren't transferred). For example: 1410 tor5010 = 01123 tor 12123 = 10213 = 3410.

Petya wrote numbers a and c on a piece of paper. Help him find such number b, that a tor b = c. If there are several such numbers, print the smallest one.

Input

The first line contains two integers a and c (0 ≤ a, c ≤ 109). Both numbers are written in decimal notation.

Output

Print the single integer b, such that a tor b = c. If there are several possible numbers b, print the smallest one. You should print the number in decimal notation.

Sample test(s)
input
14 34
output
50
input
50 34
output
14
input
387420489 225159023
output
1000000001
input
5 5
output
0


解题说明:此题是求三进制的运算,按照题目的意思,两个数求tor是先把两个数转换为三进制数,然后每一位单独进行累加(不进位)。题目中给出的是最后结果和一个数,求的是另外一个数,可以用结果减去另一个数即可。

#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>#include <cstring>#include <string>#include <algorithm>using namespace std;int main() {int a,b,c,p;scanf("%d %d",&a,&c);b=0;p=1;while(a||c){b+=((c%3-a%3+3)%3)*p;p*=3;a/=3;c/=3;}printf("%d\n",b);return 0;}



原创粉丝点击