CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
factor out perfect square

 



dwarnold45
Novice

Jul 19, 2011, 2:59 PM

Post #1 of 5 (1033 views)
factor out perfect square Can't Post

Hi,

I am looking for a technique where I can factor out a perfect square. For example, starting with sqrt(75), I want a result of 5*sqrt(3). The routine doesn't have to deal with the square roots signs. I can deal with those.

I just need the routine, after being fed the number 75, to return 25 and 3.

Another example: Feed the routine 72, it returns 36 and 2.

Another example: Feed the routine 486, it returns 81 and 6.

Thanks,

David


BillKSmith
Veteran

Jul 20, 2011, 6:13 AM

Post #2 of 5 (1017 views)
Re: [dwarnold45] factor out perfect square [In reply to] Can't Post

For small numbers, trial and error works fine.


Code
  

use strict;
use warnings;
use POSIX "floor";
my $test = 487;
print join( ' ', sfactor($test));

sub sfactor {
my ($n) = @_;
my $m = floor sqrt( $n/2 );
while ($m > 1) {
my $m2 = $m * $m;
if( !( $n % $m2 ) ) {
return $m2, $n/$m2;
}
$m--
}
die "No factor is a perfect square\n";
}

Good Luck,
Bill


dwarnold45
Novice

Jul 20, 2011, 7:44 AM

Post #3 of 5 (1014 views)
Re: [BillKSmith] factor out perfect square [In reply to] Can't Post

Very nice!

Thanks.

David


miller
User

Jul 22, 2011, 10:01 PM

Post #4 of 5 (977 views)
Re: [BillKSmith] factor out perfect square [In reply to] Can't Post

nice solution Bill.

One note, your division by 2 needs to be removed or you'll miss numbers with an additional 4 as divisors:


Code
use POSIX qw(floor); 

use strict;
use warnings;

my $test = 1048576; # 1024;

printf "%s * sqrt(%s)", sfactor($test);

sub sfactor {
my ($n) = @_;
my $m = floor sqrt $n;
while (1) {
my $m2 = $m * $m;
if( !( $n % $m2 ) ) {
return $m, $n / $m2;
}
$m--;
}
}


- Miller


BillKSmith
Veteran

Jul 23, 2011, 8:34 AM

Post #5 of 5 (961 views)
Re: [miller] factor out perfect square [In reply to] Can't Post

Good point. In fact, that '2' changes the result if and only if the argument is a perfect square. I should have asked the OP about the special case. Today, your guess sounds better.Smile
Good Luck,
Bill

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives