Shandrew (shandrew) wrote,
Shandrew
shandrew

perl is sooooo easy

For the last few days, Linnea has been working on Project Euler in C. Project Euler problem 16 asks to add up the digits in 2^100. Since long long int only supports up to 2^64, she wrote her own algorithm to calculate it digit by digit in a string. Anyway, i figured that since perl does everything, and since i've never looked at math limits in perl, i'd try it out...


#!/usr/bin/perl -w

use strict;
use Math::BigInt ':constant';

my $i = 2**1000000;
#my $i = 2**1000;
my $sum;

for (0..$i->length()-1) {
#print $i->digit($_);
$sum += $i->digit($_);
}

print "$sum\n";


yeah, that's 2 to the millionth power...lots of googols! Took about 20 minutes to complete.

(Ok, so you could use GMP in C...but that would probably take me about 10x longer to figure out.)
Subscribe
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.
  • 0 comments