I'm trying to solve some online puzzles, I find the biggest simple coefficient of a very large number (7393913335919140050521110339491123405991919445111971, to be precise). Looking for a solution, I came across this Perl code ( from here ):
use strict; use warnings; my $magic = <number>; sub largestprimef($); sub max($$); print largestprimef($magic); sub largestprimef($) { my $n = shift; my $i; return largestprimef(max(2, $n/2)) if($n % 2 == 0); my $sn = int( sqrt($n) ); for ( $i = 3 ; $i <= $sn ; $i += 2 ) { if ( $n % $i == 0 ) { last; } } if ( $i > $sn )
Now this algorithm seems to work! A small problem with Perl is that it does not accept really large numbers. Therefore I rewrote
my $magic = <number>;
to
my $magic = Math::BigInt->new(' <number> ');
but it just works for centuries. So I rewrote it in Java (in which I am a little more familiar), resulting in:
static final BigInteger two = new BigInteger( "2" ); public static void main( String[] args ) { BigInteger number = new BigInteger( "<number>" ); System.out.println( goAtIt( number ) ); } static BigInteger goAtIt( BigInteger prime ) { if ( isEven( prime ) ) return goAtIt( prime.divide( two ).max( two ) ); BigInteger sqrt = sqrt( prime ); BigInteger comp = new BigInteger( "3" ); while (sqrt.compareTo( comp ) > 0) { if ( prime.remainder( comp ).equals( BigInteger.ZERO ) ) break; comp = comp.add( two ); } if ( comp.compareTo( sqrt ) > 0 ) return prime; return comp.max( goAtIt( prime.divide( comp ) ) ); }
Using assistive devices (which seem accurate):
static boolean isEven( BigInteger number ) { return number.getLowestSetBit() != 0; } static BigInteger sqrt( BigInteger n ) { BigInteger a = BigInteger.ONE; BigInteger b = new BigInteger( n.shiftRight( 5 ).add( new BigInteger( "8" ) ).toString() ); while (b.compareTo( a ) >= 0) { BigInteger mid = new BigInteger( a.add( b ).shiftRight( 1 ).toString() ); if ( mid.multiply( mid ).compareTo( n ) > 0 ) b = mid.subtract( BigInteger.ONE ); else a = mid.add( BigInteger.ONE ); } return a.subtract( BigInteger.ONE ); }
But my results are always off ... and my Perl is actually not so good as to reverse engineer the source code. Does anyone know what I am missing?
== UPDATE: the problem is (somewhat) resolved in a workaround
source share