On 3/27/12 Tue  Mar 27, 2012  9:07 AM, "Somu" <som....@gmail.com> scribbled:

> Hello all!
> 
> I know this is a very elementary question. But please help me with this.
> There can be many good algorithms to find prime numbers, but being a
> starter, please correct my mistakes.
> I want to take a number as input and find out if it is prime or otherwise.
> My code is as follows:
> 
> # start
> use strict;
> use warnings;

Good start!

> 
> print "\n\nEnter a number : " ;
> my $x = 1, my $count = 0;

You can start with a value of $x = 2. Better would be to make 2 a special
case, then start with $x = 3 and increment $x by 2 each time, only testing
odd divisors.

> my $no = <>;

You should use chomp($no) to remove the new line from the end of $no. You
could also set $no to $ARGV[0] and enter the number to test on the command
line.

> print "\n\nThe number is : $no";

Most people put new lines at the end of the printed line, not the beginning.

> if( $no<2 ){
> print "\n\n$no is neither prime nor composite";

You should indent loops and if blocks to make your program more readable.

> }
> else{
> while(($x!=$no)||$count<3){

You should stop whenever $x is greater than or equal to $no, regardless of
the value of count. Otherwise, your loop will never terminate for a prime
number. You can actually stop sooner: when $x is >= sqrt($no), as no factor
of $no can be larger than sqrt($no). Take sqrt($no) only once for efficiency
and save the value in another variable.

You should also add whitespace to your lines for readability.

> if ($no%$x==0){
> $count++;
> }
> $x++;
> }
> if ($count >=3 ){
> print "\n\n$no is prime";

If $count is greater than 2, then the number is prime, provided you have
started with $x = 1. You should really stop and terminate the loop as soon
as you have found a divisor of $no, and there is no need for a count
variable, as long as start with $x = 2 or 3 and not 1.

> }
> else{
> print "\n\n$no is not prime";
> }
> }
> 
> print "\n\n";
> system "pause";

This does not work. You can pause the program and wait for a return
character by doing:

my $response = <STDIN>;




-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to