2004-03-23

Factoring Fun

Ever want to find the factors of an Integer? Well here's a nifty JavaScript version:

<script language="JavaScript"><!--
function factor(f){
  var n = f.n.value;
  if(n.length > 0){
    var c = 0;
    var d = "";
    for(var i = 2; i <= Math.sqrt(n); i += c){
      if(c < 2)
        c++;
      if(n % i == 0) {
        for(var j = 0; n % i == 0; j++)
          n /= i;
        if(d.length > 0)
          d += "*";
        d += i;
        if(j > 1)
          d += "^" + j;
      }
    }
    if(n != 1 || d.length == 0){
      if(d.length > 0)
        d += "*";
      d += n;
    }
    f.d.value = d;
  }
}
// -->
</script>

<form onSubmit="factor(this);return false;">
The prime decomposition of positive integer
<input type="text" name="n" size="24" /> is <input type="text" name="d" size="38" />.<br />
<input type="submit" value="Factor">
</form>
The prime decomposition of positive integer is .

And a VBScript version (create a file called factorer.vbs):
' Whole number factorer
' By: Scriptar
' Written on 11-20-2001
' This program will give factors for any whole number that will fit in the Long data type

Option Explicit

'No number should have more than 100 factors
Dim factorArr(100, 2), strFactorThis, factorThis

Function Factor(tlNumberToFactor)
  Dim maxFactor, numFactors, x
  
  numFactors = 0
  maxFactor = CLng(Sqr(tlNumberToFactor) + 1)
  For x = maxFactor To 2 Step -1
    If tlNumberToFactor Mod x = 0 Then
      numFactors = numFactors + 1
      factorArr(numFactors, 1) = x
      factorArr(numFactors, 2) = tlNumberToFactor / x
    End If
  Next
  
  Factor = numFactors
End Function

Sub DispFactors(tlNumberToFactor)
  Dim numFactors, msg, x
  
  numFactors = Factor(tlNumberToFactor)
  If numFactors = 0 Then
    MsgBox tlNumberToFactor & " is a prime number.", , "Factorer"
  Else
    msg = "Factors for " & tlNumberToFactor & ":"
    For x = 1 To numFactors
      msg = msg & vbCrLf & x & ") " & factorArr(x, 1) & " x " & factorArr(x, 2)
    Next
    MsgBox msg, , "Factorer"
  End If
End Sub

'If they press OK with no number or Cancel or invalid... end program
strFactorThis = ""
factorThis = 0
On Error Resume Next
Do While True
  strFactorThis = InputBox("Enter a number to factor:" & vbCrLf & "(Press Cancel to quit)", "Factorer")
  If Len(strFactorThis) = 0 Or Not IsNumeric(strFactorThis) Then Exit Do
  factorThis = CLng(strFactorThis)
  If Err.Number <> 0 Then
    MsgBox strFactorThis & " is too large a number to be factored with this program.", , "Factorer"
    Err.Clear
  Else
    If factorThis > 2 Then
      DispFactors factorThis
    Else
      MsgBox strFactorThis & " cannot be factored.", , "Factorer"
    End If
  End If
Loop
Sorry, this won't help you win $200,000. It's just for fun. F@ct0r4fuhn!™