数论 Goodnumbers

The only difference between easy and hard versions is the maximum value of n.

You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.

The positive integer is called good if it can be represented as a sum of distinct powers of 3 (i.e. no duplicates of powers of 3 are allowed).

For example:

30 is a good number: 30=33+31,
1 is a good number: 1=30,
12 is a good number: 12=32+31,
but 2 is not a good number: you can’t represent it as a sum of distinct powers of 3 (2=30+30),
19 is not a good number: you can’t represent it as a sum of distinct powers of 3 (for example, the representations 19=32+32+30=32+31+31+31+30 are invalid),
20 is also not a good number: you can’t represent it as a sum of distinct powers of 3 (for example, the representation 20=32+32+30+30 is invalid).
Note, that there exist other representations of 19 and 20 as sums of powers of 3 but none of them consists of distinct powers of 3.

For the given positive integer n find such smallest m (n≤m) that m is a good number.

You have to answer q independent queries.

Input
The first line of the input contains one integer q (1≤q≤500) — the number of queries. Then q queries follow.

The only line of the query contains one integer n (1≤n≤104).

Output
For each query, print such smallest integer m (where n≤m) that m is a good number.

Example
Input
7
1
2
6
13
14
3620
10000
Output
1
3
9
13
27
6561
19683
思路:把十进制转化为三进制再操作


```cpp
#include<stdio.h>
#include<math.h>
long long t,n,m,min,sum,flag,i,j;
long long qwe(long long x,long long y)
{
	long long n=1,m;
	while(y)
	{	    
		if(y&1)
		    n*=x;
		y >>= 1;
		x=x*x;
	}
	return n;
}
int main()
{	
	scanf("%lld",&t);
	while(t--)
	{
		scanf("%lld",&n);
		if(qwe(3,log(n)/log(3))==n)
		    m=log(n)/log(3);
		else
		{
			m=log(n)/log(3)+1;
		}
		min=qwe(3,m);
		for(i=m-1;i>=0;i--)
		{
			sum=0;flag=0;
			for(j=i;j>=0;j--)
			{
				m=qwe(3,j);
				sum+=m;
				if(sum>=n)
				{
					flag=1;
					if(sum<min)
					    min=sum;
					sum-=m;
				}
			}
			if(flag==0)
			    break;
		}
		printf("%lld\n",min);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值