Ok, try this. As pointed out by others, as written, this reads the whole number into memory to operate on it. The division sub would be trivial to change to work with file handles, only loading a bit at a time and writing out the results as it goes. The longmul sub will be a little trickier, but possible. Reference the comments by Tanktalus and ikegami. It would need to reverse the input file, operate on it, then reverse the results file.
#!/usr/bin/perl
use warnings;
use strict;
my $number;
for(0..999)
{
$number .= int(rand 9);
}
print "$number\n\n";
my ($result, $remainder) = longdiv($number, 222);
print "$result\n\nRemainder $remainder\n\n\n";
print longmul($result, 222, $remainder) . "\n";
sub longdiv {
my @digits = split //, shift;
my $demoninator = shift;
my $carry = 0;
my $out = '';
my $numerator;
while (@digits) {
$numerator = shift @digits;
$numerator += $carry * 10;
$carry = $numerator % $demoninator;
$out .= int($numerator / $demoninator);
}
$out =~ s/^0+//;
return ($out, $carry);
}
sub longmul {
my @digits = reverse split //, shift;
my $multiplier = shift;
my @remainder = reverse split //, shift if $_[0];
my $out = '';
my ($digit, $progress);
while (@digits) {
$digit = shift @digits;
if ($digit eq '.')
{
$out = '.' . $out;
next;
}
$progress += $digit * $multiplier;
$progress += shift @remainder if @remainder;
$out = ($progress % 10) . $out;
$progress = int($progress / 10);
}
$out = $progress . $out;
return $out;
}
|