Click to See Complete Forum and Search --> : Help with math script


jacci
12-12-2005, 09:24 AM
Hi, my name is jacci, and i just joined. I am relatively new to coding and this is my first foray into javascripting. So far i have just been using scripts i have found.

Now i have found one though that I really like, but doesn't quite work exactly as it should. After many many hours of struggling with it, i have finally figured out how to alter the script to stop the function results coming up as an alert, instead, getting them to show in a text box within the form field and I am very proud of myself for figuring that out.... :D

But now i am faced with too big a problem for me to solve. So i am coming to the experts and hope someone is kind enough to take a look for me.

it is a script to find the common factors of two numbers, only problem is, it always misses a factor. For example, the common factors of 10 and 20 should be 1, 2, 5 and 10 , but the script doesn't allow for one of the input variables to be a factor as well :mad: It misses out on 10 as a common factor

this is a copy of the original script, not the one i have tinkered with (which aside from the missing factor, i am pleased to report works just fine)

thanking you in advance

jacs



<script>

function findFactors() {

var f = document.forms[0];

var value1 = parseInt( f.composite1.value );

var value2 = parseInt( f.composite2.value );

if ( isNaN( value1 ) || isNaN( value2 ) ) {
alert( "Please enter valid number values" );
f.reset();
return;
}

if ( value1 == 0 || value2 == 0 ) {
alert( "No common factors" );
return;
}

value1 = Math.abs( value1 );
value2 = Math.abs( value2 );
var answer = "1";
for ( var x = 2; x < Math.min( value1, value2 ); x ++ ) {
var check1 = value1 / x;
if ( check1 == Math.round( check1 ) ) {
var check2 = value2 / x;
if ( check2 == Math.round( check2 ) ) {
answer += ", " + x;
}
}
}

alert( "value1 = " + value1 + "\nvalue2 = " + value2 + "\nCommon Factors: " + answer );
}
</script>

TheBearMay
12-12-2005, 09:38 AM
Try changing your for loop to read:

for ( var x = 2; x < Math.min( value1+1, value2+1 ); x ++ ) {

jacci
12-12-2005, 09:52 AM
You are a genius Oh mighty TheBearMay and I bow down before your magnificence!!!!


Seriously though, thank you soooo much. That did the trick beautifully.

And the sad fact is i probably never would have figured that out on my own, took me about four hours to change the result output and that was pretty easy I guess. Ahhh it is no fun to be the novice.

I thank you once again, I really do appreciate that very much, and most especially for such a speedy reply.

thanks eternally


jacs

TheBearMay
12-12-2005, 10:00 AM
When you make as many mistakes as I have you occasionally find a nugget or two. :D

Glad to be of service.