Tag Archives: Perl

Project Euler 12

So I finished problem 12 from Project Euler. I made it via a brute force attack in Perl.

#!/usr/bin/env perl

use warnings;
use strict;

my $j = 0;
for (my $x=1; $x <= 1000000; $x++) {
        $j = $j + $x;
        my $dividend = 0;
        print "j is $j, x is $x and dividend is $dividend.\n";
        for (my $z=1; $z <= ($j + 1); $z++) {
                if ($j%$z == 0) {
                        $dividend = $dividend + 1;
                        print "$z is dividend of $j and $j has dividend $dividend.\n"; 
                        if ($dividend > 501) {
                                print "$z is dividend of $j and $j has dividend $dividend.\n"; 
                                exit; }
                                }
                        }
                }

and with some logic in Python. The python script can be divided in three part, first we find the triangle number, then we calculate the numbers that factor the triangle number and place it into an array and the last step would be to calculate how many divisors the triangle number has.

#!/usr/bin/python 

import math

# Start the triangle by one
triangle = 0
for x in range(1, 100000):
        triangle = x*(x+1)/2
        #print "triangles is ", triangle

# We factor the triangle into prime numbers
        def primefactors(x):
                factorlist=[]
                loop=2
                while loop<=x:
                        if x%loop==0:
                                x/=loop
                                factorlist.append(loop)
                        else:
                                loop+=1
                return factorlist
        #print primefactors(triangle)

# We calculate the number of divisors of the triangle number
        divisor = 1
        for z in set(primefactors(triangle)):
                #print "{0}\t{1}".format(z,primefactors(triangle).count(z))
                divisor = (primefactors(triangle).count(z) + 1) * divisor
                #print "Triangle", triangle," has ", divisor," divisors."
                if (divisor > 500):
                        print "Triangle", triangle," has ", divisor," divisors."
                        quit()

Reference:
1) Integer Factorization
2) Triangular numbers
3) Number of divisors of a number

Project Euler

So I was looking around for some programming information and found Project Euler. They have a number of problems to program. You can choose any programming language, it’s just to enhance your programming abilities.

So here is the answer to problem number one.

#!/usr/bin/perl

use warnings;
use strict;

my $sum;
my $count;

for ($count = 0; $count < 1000; $count ++) {
        if (($count % 3 == 0) || ($count % 5 == 0)) {
                $sum = $count + $sum;
                print "\$sum is $sum\n"; }
        }

It’s a really simple exercise. You just need to sum of all the multiples of 3 or 5 below 1000.

Savings script

So I was thinking about writing a script to calculate the savings over a certain matter of time and came up with the following.

#!/usr/bin/perl

use warnings;
use strict;

print "What is the yield?\n";
my $yield = <>;
print "How many years?\n";
my $years = <>;
print "How much money saved anually?\n";
my $savings = <>;
my $i;
my $new_savings = 0;

for($i = 1; $i <= $years; $i++) {
	$new_savings = $savings + $new_savings;
	$new_savings = $new_savings + $new_savings*($yield/100);
	printf "Savings for year $i are \$%.2f.\n", $new_savings;
}

Below is an usage example.

[19:43:04] xavi@ubuntu:/tmp $ ./yield.pl
What is the yield?
5.0
How many years?
5
How much money saved anually?
10000
Savings for year 1 are $10500.00.
Savings for year 2 are $21525.00.
Savings for year 3 are $33101.25.
Savings for year 4 are $45256.31.
Savings for year 5 are $58019.13.
[19:43:18] xavi@ubuntu:/tmp $

This just gives an idea of the money that can be saved over a short period of time with a five percent yield. It’s a really simple script.

Apache visits with Perl

Here is another Perl script. This one given an Apache log file will tell you the number of hits per IP. Here is the code.

#!/usr/bin/perl -w

use strict;
use diagnostics;

if( $#ARGV != 0 ){
        print "Usage: ./parser.pl &lt;logfile&gt;\n"; 
        exit 1; }

# Opening logfile
open FILE, "$ARGV[0]" or die $!;

# Defining variables
my @lines = &lt;FILE&gt;;
my @ip;
my $items = scalar(@lines);
my ($i, $value); 
my %hits;

# Removing IP addresses from logfile and counting the hits per IP.
for ($i = 0; $i &lt; $items; $i++)
        { @ip = split (/ /, $lines[$i]);
        if (exists $hits{$ip[0]}) {
                $hits{$ip[0]} = $hits{$ip[0]}+1; 
                chomp($hits{$ip[0]}); } 
        else {  $hits{$ip[0]} = 1; } 
        }

# Ordering and printing the hits per IP.
foreach $value (sort {"$hits{$b}" &lt;=&gt; "$hits{$a}" } keys %hits)
        { print "$value made $hits{$value} hits.\n"; }

Here is an usage example.

xavi@debianserver:~/Perl$ ./parser.pl /tmp/apachelog 
12.130.86.9 made 106 hits.
208.111.39.192 made 89 hits.
67.195.114.231 made 42 hits.
98.14.22.97 made 27 hits.
208.54.45.78 made 17 hits.
213.5.71.12 made 16 hits.
199.106.237.37 made 15 hits.
66.249.67.212 made 15 hits.
208.54.45.62 made 12 hits.
87.250.252.242 made 9 hits.
174.121.74.234 made 6 hits.
188.187.102.74 made 6 hits.
208.54.45.72 made 5 hits.
64.40.121.184 made 4 hits.
206.196.125.114 made 3 hits.
207.46.13.94 made 2 hits.
220.181.146.169 made 2 hits.
142.166.170.101 made 2 hits.
220.181.94.225 made 2 hits.
142.166.170.100 made 2 hits.
65.52.108.60 made 2 hits.
207.46.199.182 made 2 hits.
207.46.13.101 made 2 hits.
208.54.45.56 made 2 hits.
209.2.233.223 made 1 hits.
67.210.218.102 made 1 hits.
66.249.67.66 made 1 hits.
220.181.7.54 made 1 hits.
207.46.199.199 made 1 hits.

As usual, suggestions are always welcome.

Check your stocks with Perl

I wrote this small script to check the value of stocks with Perl. It doesn’t shows the value of the stock in the pre and post market, but it does its job.

     1  #!/usr/bin/perl -w
     2
     3  use strict;
     4  # Loading modules with use
     5  use LWP::UserAgent;
     6  use HTTP::Request;
     7  use HTML::Strip;
     8
     9  my $length = $#ARGV + 1;
    10  my $stock;
    11
    12  if ($length <= 0) {
    13          print "Usage: ./stock.pl ticker1 ticker2 .. tickern\n";
    14          exit 1 }
    15
    16  my $ua = LWP::UserAgent->new;
    17  #$ua->agent("Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");
    18  $ua->agent("Perl Script checking stock value");
    19
    20  # Getting Google finance site website
    21  foreach $stock (0 .. $#ARGV) {
    22  my $url = "http://www.google.com/finance?q=$ARGV[$stock]";
    23  my $req = HTTP::Request->new(GET => $url);
    24  my $response = $ua->request($req);
    25  my $content = $response->content();
    26
    27  # Splitting the HTML code previously requested
    28  my @values = split(' ', $content);
    29  my @valor = grep(/ref_(\d+)_l/, @values);
    30
    31  foreach my $val (@valor) {
    32          # Using HTML::Strip to clean HTML tag
    33          my $hs = HTML::Strip->new();
    34          my $clean_text = $hs->parse( $val );
    35          $hs->eof;
    36          # Using split to remove > 
    37          my @value_2 = split(/\>/, $clean_text);
    38                  # Printing stock value after removing >
    39                  print "$ARGV[$stock] price is $value_2[1]\n"; 
    40    }
    41  }

Here is an usage example.

xavi@liberdade:/tmp$ ./stockparse.pl ge cat
ge price is 16.05
cat price is 69.72
xavi@liberdade:/tmp$ 

Suggestions are always welcome.