Solver Find factors of any number
Algebra
->
Divisibility and Prime Numbers
-> Solver Find factors of any number
Log On
Algebra: Divisibility and Prime Numbers
Section
Solvers
Solvers
Lessons
Lessons
Answers archive
Answers
Source code of 'Find factors of any number'
This Solver (Find factors of any number)
was created by by
ichudov(507)
:
View Source
,
Show
,
Put on YOUR site
About ichudov
:
I am not a paid tutor, I am the owner of this web site!
==section input Find all factors of *[input a=24]. ==section solution perl my $orig_a = $a; #my $b = $cgi->param( 'b' ); unless( $a =~ /^\d+$/ ) { print "Natural number expected instead of '$a'.\n"; return; } if( $a == 0 || $a == 1 ) { print "$a is a special case and does not get factored"; return; } if( $a > 2000000000 ) { print "$a is too BIG, use a number less than two billion\n"; return; } my $count = 0; my @factors = (); my $min_i = 2; my $work = ""; while( $a > 1 ) { my $imax = sqrt( $a )+1; my $nothing_done = 1; for( my $i = $min_i; $i < $imax && $i < $a; $i++) { #print STDERR "i=$i, a=$a.\n"; if( ($a % $i) == 0 ) { push @factors, $i; my $a1 = int( ($a+0.1)/$i ); $work .= "$a is divisible by $i: $a = $a1 * $i.\n"; $a = $a1; $nothing_done = 0; last; } else { $min_i = $i+1; } } if( $nothing_done ) { push @factors, $a; last; } } if( $a > 1 ) { $work .= "$a is not divisible by anything.\n"; } if( $#factors > 0 ) { print "$orig_a is NOT a prime number: $orig_a = " . join( " * ",@factors ) . "<BR>"; } else { print "$orig_a is a prime number\n"; } print "<H3>Work Shown</H3>\n<PRE>\n$work\n</PRE>"; print 'This calculation used this <A HREF=Prime_factorization_algorithm.wikipedia>Prime Factorization Algorithm</A>.<BR>'; $factors = join( ",", @factors ); ==section output factors ==section check a=6 factors=2,3