A. Link/Cut Tree
Programmer Rostislav got seriously interested in the Link/Cut Tree data structure, which is based on Splay trees. Specifically, he is now studying the expose procedure.
Unfortunately, Rostislav is unable to understand the definition of this procedure, so he decided to ask programmer Serezha to help him. Serezha agreed to help if Rostislav solves a simple task (and if he doesn't, then why would he need Splay trees anyway?)
Given integers l, r and k, you need to print all powers of number k within range from l to r inclusive. However, Rostislav doesn't want to spent time doing this, as he got interested in playing a network game called Agar with Gleb. Help him!
Input
The first line of the input contains three space-separated integers l, r and k (1 ≤ l ≤ r ≤ 1018, 2 ≤ k ≤ 109).
Output
Print all powers of number k, that lie within range from l to r in the increasing order. If there are no such numbers, print "-1" (without the quotes).
題目簡單來說就是輸出在區間[l,r]上所有k^x。水題,但是要留意l,r的最大值可爲10^18,k的最大值可達到10^9若不留意比較方法可能會造成數據溢出而導致結果出錯。
所以我在做的時候決定用tem存儲當前可能會輸出的數,將r/tem與k比較以此來決定是否輸出結束,可以防止數據溢出。
代碼:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
long long l,r,k;
while (scanf("%I64d%I64d%I64d",&l,&r,&k)==3)
{
long long tem=1;
int cnt=0;
if (k==1)
{
if (l<=1&&r>=1)
printf("%I64d\n",k);
else
printf("-1\n");
}
else
{
if (tem<l)
{
while (l/tem>=k)
tem*=k;
}
if (tem<l&&r/tem<k)
printf("-1\n");
else
{
if (tem<l)
tem*=k;
printf("%I64d",tem);
while (r/tem>=k)
{
tem*=k;
printf(" %I64d",tem);
}
printf("\n");
}
}
}
return 0;
}