Perl factorization script

Discussion in 'Programming and Homework Questions' started by CobraPizza, Feb 12, 2013.

Thread Status:
Not open for further replies.
  1. CobraPizza

    CobraPizza Notebook Guru

    Reputations:
    0
    Messages:
    58
    Likes Received:
    0
    Trophy Points:
    15
    I am writing a factorization script, in Perl. So far I made this

    #!/usr/bin/perl

    print "\nInteger input for factorization: ";
    $n = <STDIN>;

    chomp $n;

    if ($n > 0){
    $res2 = 1;
    while ($n > 1){
    $res1 = ($n - 1);
    $res3 = $res1 * $res2;
    $res2 = $res3;
    $n--;
    }
    $res = $res3 * $n;
    print "Result: ";
    print "$res\n";
    }

    elsif ($n = 0){
    print "'Result: 0'\n";
    }

    My problem is, that it wont print the "elsif" command, when input is 0 and doesn't give the result for the input integer $n but for $n-1. Can anybody help me debug this?
     
  2. CobraPizza

    CobraPizza Notebook Guru

    Reputations:
    0
    Messages:
    58
    Likes Received:
    0
    Trophy Points:
    15
    Nevermind, found the flaw
     
  3. masterchef341

    masterchef341 The guy from The Notebook

    Reputations:
    3,047
    Messages:
    8,658
    Likes Received:
    4
    Trophy Points:
    206
    Like many programming languages, Perl uses double equal sign for equality check, and single equal sign for assignment to the left.

    Your perl script as is doesn't execute because it contains a syntax error. Your algorithm also produces incorrect output as you've noticed for (almost) all cases, but you may not have considered that it also produces incorrect output for the "0" case, which you hard coded. You also say that you're trying to a "factorization" algorithm, but you're clearly going for a "factorial", which is completely different.

    I'm not writing "epic perl" or an "epic factorial" algorithm, but you're solution is over complex, which might be why you are getting caught up in the details. You've got lots of variables and swapping around and the conditional branch for the zero case, all of which is unnecessary. Here's a simpler algorithm that produces correct output for the "0" case as well.

    #!/usr/bin/perl

    print "\nInput an integer to calculate its factorial: ";
    $n = <>;


    chomp $n;
    $res = 1;


    while ($n > 1)
    {
    $res = $res * $n;
    $n = $n - 1;
    }


    print "Result: " + $res + "\n";
     
  4. akashram

    akashram Notebook Enthusiast

    Reputations:
    0
    Messages:
    11
    Likes Received:
    1
    Trophy Points:
    6
    Perl factorization script is working perfectly for me. Thanks for sharing the script.
     
Loading...
Thread Status:
Not open for further replies.

Share This Page