首页 > 代码库 > POJ 2800 Joseph's Problem
POJ 2800 Joseph's Problem
给n 和 k 求: ∑1<=i<=n(k mod i).
p = k/i
k mod i = k - p * i
k mod ( i + 1 ) = k - p * ( i + 1 ) = k mod i - p
k mod ( i + 2 ) = k - p * ( i + 2 ) = k mod i - 2 * p
对于连续的 i ,很多p都是一样的 . 相差的部分是一个等差数列 ,
i 的 范围是 从 i 到 min(k/p,n) 如果 p == 0 则 一直延续到最后
Joseph‘s Problem
Description Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph‘s problem. It is stated as follows.
Of course, all of you know the way to solve this problem. The solution is very short, all you need is one cycle: r := 0; for i from 1 to n do r := (r + k) mod i; return r; Here "x mod y" is the remainder of the division of x by y, But Joseph is not very smart. He learned the algorithm, but did not learn the reasoning behind it. Thus he has forgotten the details of the algorithm and remembers the solution just approximately. He told his friend Andrew about the problem, but claimed that the solution can be found using the following algorithm: r := 0; for i from 1 to n do r := r + (k mod i); return r; Of course, Andrew pointed out that Joseph was wrong. But calculating the function Joseph described is also very interesting. Given n and k, find ∑1<=i<=n(k mod i). Input The input file contains n and k (1<= n, k <= 109). Output Output the sum requested. Sample Input 5 3 Sample Output 7 Source Northeastern Europe 2005 |
[Submit] [Go Back] [Status] [Discuss]
/* *********************************************** Author :CKboss Created Time :2015年02月02日 星期一 10时53分55秒 File Name :POJ2800.cpp ************************************************ */ #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <string> #include <cmath> #include <cstdlib> #include <vector> #include <queue> #include <set> #include <map> using namespace std; typedef long long int LL; LL n,k; int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); while(cin>>n>>k) { LL ret=0; for(int i=1;i<=n;i++) { LL p = k/i; if(p==0) { ret += (n-i+1)*k; break; } else { LL q = k/p; if(q>n) q = n; LL md = k%i; LL num = q-i+1; LL temp = md*num-(num-1)*num/2*p; ret += temp; i=q; } } cout<<ret<<endl; } return 0; }
POJ 2800 Joseph's Problem
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。