-
Notifications
You must be signed in to change notification settings - Fork 0
/
prime_number.pl
95 lines (87 loc) · 1.77 KB
/
prime_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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
####################################################
# script name : prime_number.pl
# description : print all prime numbers less than given number
# author : Dai Nguyen-Van
# email : dainv1989@gmail.com
# creation date : 11/10/2013
####################################################
#!/usr/bin/perl
# check a number is prime or not
# return 1 if true
# return 0 if false
sub is_prime
{
my $number = $_[0];
my $sqrtnum = sqrt($number);
# if the checking number is an even number
if ($number > 2 && $number%2 == 0)
{
return 0;
}
# if the checking number is an odd number
elsif ($number%2 == 1)
{
my $i = 3;
while ($i <= $sqrtnum)
{
if ($number % $i == 0)
{
return 0;
}
$i += 2;
}
if ($i >= $sqrtnum)
{
return 1;
}
}
else
{
return 1;
}
}
# 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);
my $max = 0;
# determine max number in file
foreach (@content)
{
if ($_ > $max)
{
$max = $_;
}
}
# calculate all prime number less than max value in file
# push result to an array
my @primes = ();
for (my $i = 2; $i <= $max; $i++)
{
if ((&is_prime($i)) == 1)
{
push(@primes, ($i));
}
}
# print result
foreach (@content)
{
if ($_ > 1)
{
my $j = 0;
while (($primes[$j] <= $_) && ($j <= $#primes))
{
if ($j > 0)
{
print ",";
}
print "$primes[$j]";
$j++;
}
print "\n";
}
}
# close file handle
close DATA;