[LON-CAPA-users] prime factorization
Gerd Kortemeyer
lon-capa-users@mail.lon-capa.org
Thu, 20 Mar 2008 12:50:56 -0400
Hi,
On Mar 19, 2008, at 6:39 PM, Justin Gray wrote:
>
> However, I do not know how to modify this problem to test whether
> an integer has been factored into primes. The example below will
> accept 60 as a correct answer. :(
>
> <problem>
> <script type="loncapa/perl">
> $answer = "2^2*3*5";
> </script>
> <startouttext />
> Find the prime factorization: <p></p>
>
> <m>$60 = $</m>
> <endouttext />
>
> <mathresponse cas="maxima" answerdisplay="$answer" args="$answer">
> <answer>is(RESPONSE[1] = LONCAPALIST[1]);</answer>
>
>
> <textline readonly="no" size="40" />
> </mathresponse>
> </problem>
I should have read this in order. The example below is probably more
what you want than what I sent yesterday - it'll accept "5*3*2^2" or
"2*3*5*2", but not "60" or "4*15":
<problem>
<script type="loncapa/perl">@primes=(2,3,5,7,11,13,17,19,23); # prime
numbers
$nfactors=&random(3,6,1); # number of factors
$number=1;
@factors=();
for ($i=1;$i<=$nfactors;$i++) {
$newprime=$primes[&random(0,$#primes,1)];
$number*=$newprime;
push(@factors,$newprime);
}
$answer=join('*',sort{$a<=>$b}(@factors));</script>
<startouttext />Factorize $number into primes.<endouttext />
<customresponse answerdisplay="$answer">
<answer type="loncapa/perl">if ($submission!~/^[\d\s\*\^]+$/)
{ return 'WANTED_NUMERIC'; }
$submission=~s/(\d+)\^(\d+)/&expanded($1,$2)/ge;
@submission=sort(split(/\s*\*\s*/,$submission));
@answer=sort(@factors);
if ($#answer!=$#submission) { return 'INCORRECT'; }
for ($i=0;$i<=$#answer;$i++) {
if ($answer[$i]!=$submission[$i]) { return 'INCORRECT'; }
}
return 'EXACT_ANS';
sub expanded {
my ($n,$e)=@_;
my $output=$n;
for (my $i=2;$i<=$e;$i++) {
$output.='*'.$n;
}
return $output;
}</answer>
<textline readonly="no" />
</customresponse>
</problem>