Burning Midnight Oil

二分
注意细节:
n<k时
i会不会溢出

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int n,k,sum,i,mid=1,ans=1;
    scanf("%d %d",&n,&k);
    int low=1;
    int high=n;
    int ok=1;
    while(low<=high&&ok==1)
    {
        if(low==high)ok=0;
        int mid=(low+high)/2;
        sum=mid;
        for(i=k; mid/i>0; i*=k) //不能写mid/i!=0,因为mid/i>0时一定能保证i在int范围内,但不能保证i*k不会溢出
            sum+=mid/i;
        if(sum<n)
            low=mid+1;
        if(sum>=n)
        {
            high=mid-1;
            ans=mid;
        }
    }
    printf("%d\n",ans);
    return 0;
}


你可能感兴趣的:(Burning Midnight Oil)