Zack
Zack

Reputation: 13952

Recursion issues with VBscript

I am trying to implement some recursion in vbscript.

Function largest_prime_factor (ByVal num)

    For i = 2 to num/2
        If num mod i = 0 Then   'this number is not prime
            largest_prime_factor (num / i)
        End If
    Next

    largest_prime_factor = num ''if at this point, we have reached the largest prime

End Function

As you can see, it is a script that is basically designed to give me the largest prime factor of a number. However, this script still spits back the imputed number at me when I run a print. After debugging, I have found that the script will indeed enter the conditional inside the for loop, but then it will NOT recurse (ie: it will keep running through the for loop and then just end after that point)

What did I miss about recursion in VBscript? I also tried something to the effect of

largest_prime_factor = largest_prime_factor (num / i)

Inside the conditional and this didn't work either.

Upvotes: 3

Views: 4058

Answers (1)

Amol Chavan
Amol Chavan

Reputation: 3970

In code posted above, you have made two minor mistakes

  1. You have created function that returns number, while calling it recursively you should get that number in variable ‘num’ for further processing.
  2. Second mistake you have made that you have not exited from loop after you getting desired output. That causes to looping further until i = num & you will have your answer as 1 in all cases.

working code ---

Function largest_prime_factor (ByVal num)
 For i = 2 to num/2
        If num mod i = 0 Then   'this number is not prime
              num= largest_prime_factor (num / i)
              Exit For 
        End If
 Next
largest_prime_factor = num ''if at this point, we have reached the largest prime
End Function

Upvotes: 4

Related Questions