Problem:
Given a number, determine if it is prime or not.
Input Format:
t=number of test cases
followed by t lines having 1 number
followed by t lines having 1 number
Output Format:
YES or NO for each input
YES or NO for each input
Constraints:
none
none
Sample Input
4
6
1333
45611
5179
6
1333
45611
5179
Sample Output:
NO
NO
NO
YES
NO
NO
NO
YES
Explanations:
6 is not prime since can be dived by 2 and 3. 5179 is prime since can be divided by 1 and 5179 only and no other number
6 is not prime since can be dived by 2 and 3. 5179 is prime since can be divided by 1 and 5179 only and no other number
Solution:
my $number = shift;
my $str = 2;
my $sqrt = sqrt $number;
while(1) {
if ($number%$str == 0) {
return 'NO';
}
if ($str < $sqrt) {
$str++;
} else {
return 'YES';
}
}
}
chomp($t=<STDIN>);
for($i=0;$i<$t;$i++)
{
chomp($n=<STDIN>);
push(@out,prime($n));
}
foreach(@out)
{
print "$_\n";
}
Tips:
Check the function used to determine prime number
No comments:
Post a Comment