File tree Expand file tree Collapse file tree 1 file changed +63
-0
lines changed
Expand file tree Collapse file tree 1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change 1+ program JosephusProblem;
2+
3+ { $mode objfpc}{ $H+}
4+
5+ uses
6+ Classes,
7+ SysUtils;
8+
9+ procedure ShowUsage ;
10+ begin
11+ Writeln(' Usage: please input the total number of people and number of people to skip.' );
12+ Halt(1 );
13+ end ;
14+
15+ function ParseInteger (const S: string; out Value : integer): boolean;
16+ begin
17+ Result := TryStrToInt(Trim(S), Value );
18+ end ;
19+
20+ function Josephus (TotalPeople, SkipCount: integer): integer;
21+ var
22+ CurrentCount, HighestPowerOf2: integer;
23+ begin
24+ if (SkipCount < 1 ) or (TotalPeople < 1 ) then ShowUsage;
25+
26+ // If skip = 1, that means that survivor is the last person
27+ if SkipCount = 1 then
28+ begin
29+ Result := TotalPeople;
30+ Exit;
31+ end ;
32+
33+ if SkipCount = 2 then
34+ begin
35+ HighestPowerOf2 := 1 ;
36+ while (HighestPowerOf2 shl 1 ) <= TotalPeople do
37+ HighestPowerOf2 := HighestPowerOf2 shl 1 ;
38+
39+ Result := 2 * (TotalPeople - HighestPowerOf2) + 1 ;
40+ Exit;
41+ end ;
42+
43+ Result := 0 ;
44+
45+ for CurrentCount := 2 to TotalPeople do
46+ Result := (Result + SkipCount) mod CurrentCount;
47+
48+ Result := Result + 1 ;
49+ end ;
50+
51+ var
52+ TotalPeople, SkipCount: integer;
53+ begin
54+ if ParamCount <> 2 then
55+ ShowUsage;
56+
57+ if not ParseInteger(ParamStr(1 ), TotalPeople) then
58+ ShowUsage;
59+ if not ParseInteger(ParamStr(2 ), SkipCount) then
60+ ShowUsage;
61+
62+ Writeln(Josephus(TotalPeople, SkipCount));
63+ end .
You can’t perform that action at this time.
0 commit comments