CodeForces 597A(公式+技巧)
阿新 • • 發佈:2018-12-24
I - Divisibility
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d
& %I64u
),按照上面的方法就能做出來了!
程式碼:
方法2: 思路: 因為在0<=a<=b的時候有這個公式sum=b/k-(a-1)/k;所以我們可以想辦法將其他區間也轉化成這種情況; 總共有三種情況:a>0&&b>0 sum=b/k-(a-1)/k; a<0&&b<0 sum=-a/k-(-b-1)/k; a<=0&&b>=0 sum=-a/k+1+b/k; 程式碼:
Description
Find the number of k-divisible numbers on the segment [a, b]. In other words you need to find the number of such integer values x thata ≤ x ≤ b and x is divisible by k.
Input
The only line contains three space-separated integers k , a and b (1 ≤ k ≤ 1018; - 1018 ≤ a ≤ b ≤ 1018).
Output
Print the required number.
Sample Input
Input1 1 10Output
10Input
2 -4 4Output
5方法1: 思路: 簡單的思路,就是先從a開始,找到第一個能被k整除的數t,然後跟b比較,如果比b大,那麼就不存在,輸出0,否則的話就看從k到b有多少個k,結果輸出k+1; 但是在找第一個能被k整除的數的時候,要分a是正數還是負數,如果是正數的話,就直接在a的基礎上加上k-a%k(也就是大於a能夠取餘k的最小的數); 如果是負數的話,用a加上多餘的那部分(-a%k),就將那部分給抵消了(滿足大於a能夠取餘k的最小的數
//A了 #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int main() { __int64 k,a,b; while(scanf("%I64d%I64d%I64d",&k,&a,&b)!=EOF) { __int64 t,u; u=a%k; if(u==0) { t=a; } else { if(u<0) { u=-u; t=a+u;//因為負的時候是將它的餘數往上加的才能是大於a的, }//負數應該和正數是對稱的!!! else { t=a+(k-u); } } if(t<=b) { __int64 sum=1; sum+=(b-t)/k; printf("%I64d\n",sum); } else { printf("0\n"); } } return 0; }
方法2: 思路: 因為在0<=a<=b的時候有這個公式sum=b/k-(a-1)/k;所以我們可以想辦法將其他區間也轉化成這種情況; 總共有三種情況:a>0&&b>0 sum=b/k-(a-1)/k; a<0&&b<0 sum=-a/k-(-b-1)/k; a<=0&&b>=0 sum=-a/k+1+b/k; 程式碼:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define INF 1000000000000000000
using namespace std;
int main()
{
__int64 k,a,b;
while(scanf("%I64d%I64d%I64d",&k,&a,&b)!=EOF)
{
__int64 sum;
if(a>0&&b>0)
sum=b/k-(a-1)/k;
else if(a<0&&b<0)
{
sum=-1*a/k-(-1*b-1)/k;
}
else if(a<=0&&b>=0)
{
sum=-1*a/k+1+b/k;
}
printf("%I64d\n",sum);
}
return 0;
}