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

dwarnold45
Novice

Jul 19, 2011, 2:59 PM

Views: 1750
 factor out perfect square
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

Views: 1734
 Re: [dwarnold45] factor out perfect square
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

Views: 1731
 Re: [BillKSmith] factor out perfect square
Very nice!

Thanks.

David

miller
User

Jul 22, 2011, 10:01 PM

Views: 1694
 Re: [BillKSmith] factor out perfect square
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

Views: 1678
 Re: [miller] factor out perfect square
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.
Good Luck,
Bill