VBscript 的递归问题 [英] Recursion issues with VBscript

查看:48
本文介绍了VBscript 的递归问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 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

如您所见,它是一个脚本,基本上旨在为我提供一个数字的最大质因数.然而,当我运行打印时,这个脚本仍然向我吐出推算的数字.调试后,我发现脚本确实会在 for 循环中输入条件,但是它不会递归(即:它将继续通过 for 循环运行,然后在该点之后结束)

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)

我对 VBscript 中的递归有什么误解?我也尝试了一些

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.

推荐答案

在上面发布的代码中,您犯了两个小错误

In code posted above, you have made two minor mistakes

  1. 您已经创建了返回数字的函数,在递归调用它时,您应该在变量num"中获取该数字以供进一步处理.
  2. 您犯的第二个错误是在获得所需输出后没有退出循环.这会导致进一步循环,直到 i = num &在所有情况下,您的答案都是 1.

工作代码---

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

这篇关于VBscript 的递归问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆