-
Notifications
You must be signed in to change notification settings - Fork 0
/
happy_number.pl
56 lines (50 loc) · 1.05 KB
/
happy_number.pl
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
####################################################
# script name : happy_number.pl
# description :
# author : Dai Nguyen-Van
# email : dainv1989@gmail.com
# creation date : 17/10/2013
####################################################
#!/usr/bin/perl
sub is_happy
{
my %set;
my $number = $_[0];
while ($number > 1 && (!exists($set{$number})))
{
# add number to hash table
$set{$number} = 0;
# total square of all constituent numbers
my @nums = split("",$number);
$number = 0;
foreach $item(@nums)
{
$number += $item**2;
}
}
# return value
if ($number == 1)
{
return 1;
}
else
{
return 0;
}
}
# open file in read-only mode
# read content of input file
# remove all end of line character (EOL)
open (DATA, "<", $ARGV[0]) or die $!;
@content = <DATA>;
chomp(@content);
foreach (@content)
{
# if line is not empty
if ($_ ne "")
{
print &is_happy($_);
print "\n";
}
}
close(DATA);