aboutsummaryrefslogtreecommitdiff
path: root/challenge-164/deadmarshal/pascal/ch2.pas
blob: 90a7250e824c75f89d8f3c4a77a36e86d1f6fc99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
program Ch2;

{$mode objfpc}

uses
   SysUtils,Math,Generics.Collections;

function SumSquares(N:Integer):Integer;
begin
   Result := 0;
   while N <> 0 do
   begin
      Result := Result + Trunc(Power((N mod 10),2));
      n := N div 10;
   end;
end;

function IsHappy(N:Integer):Boolean;
type
   TMap = specialize THashMap<Integer,Integer>;
var
   Value:Integer;
   Map:TMap;
begin
   Map := TMap.Create;
   while True do
   begin
      Map.Add(N, 1);
      N := SumSquares(N);
      if(N = 1) then
      begin
	 Result := True;
	 break;
      end;
      Map.TryGetValue(N,Value);
      if(Value <> 0) then
	 begin
	    Result := False;
	    break;
	 end;
   end;
   FreeAndNil(Map);
end;

procedure HappyNumbers;
var
   I,Count:Integer;
begin
   I := 0;
   Count := 0;
   while Count < 8 do
   begin
      if IsHappy(I) then
      begin
	 Write(I, ' ');
	 Inc(Count);
      end;
      Inc(I);
   end;
end;

begin
   HappyNumbers;
end.