NAGAY - Joseph’s Problem

no tags 

Joseph likes taking part in programming contests. His favorite problem is, of course, Joseph’s problem.
It is stated as follows.
                           There are n persons numbered from 0 to n − 1 standing in a circle. The person number
                           k, counting from the person number 0, is executed. After that the person number k of the
                           remaining persons is executed, counting from the person after the last executed one. The
                           process continues until only one person is left. This person is a survivor. The problem is,
                           given n and k detect the survivor’s number in the original circle.

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 sum of (k%i) from i=1 to n;

Input

The input file contains n and k (1 <= n, k <= 10^18)

Output

Output the sum requested.

Example

Input:
5 3

Output:
7

hide comments
cjn2007: 2021-10-28 08:11:57

AC in one go!

nadstratosfer: 2017-12-14 04:46:39

Judge solution can't handle many cases, some verifiable by brute force. Mine does =) Enjoyed coding it, even if it costed me an hour longer than what seems to be needed for AC. Nice logic.

Piyush Raman Srivastava: 2013-06-19 09:51:41

just some observations needed to solve it. :)

Sandeep Singh Jakhar: 2012-02-17 05:00:15

@Vimal Yes

Vimal Raj Sharma: 2012-02-16 16:31:07

Will the solution fit in long long ?

[Rampage] Blue.Mary: 2012-02-16 10:04:58

Mmm, O(sqrt(k)) CAN pass.


Added by:Azat Taryhchiyev
Date:2012-02-16
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64 PERL PERL6
Resource:ACM ICPC 2005–2006, Northeastern European Regional Contest St Petersburg – Barnaul – Tashkent –