递归C语言找素因子,试图解决没有递归的最大素因子 - Ruby

我遇到了一个叫做欧拉项目的网站,一切都很顺利,直到我遇到第三个问题 - 最大的主要因素。我不想用递归来解决它。我在网上看到他们使用Math.sqrt的解决方案,我也不想使用它。固执,我知道。试图解决没有递归的最大素因子 - Ruby

我想用循环和if语句解决它。我认为输入是一个奇数。这是我的代码。如果num = 99,输出保持为[3],我不知道为什么。我试图在每个步骤都放置一个puts语句来查看输出的内容。我意识到的一个问题是数组#p在每个循环后都没有重置。我尝试了array.clear,但这并没有多大帮助。有人能指出我正确的方向吗?有没有关于数组,循环和if语句的一些基本方面,我没有得到?

def prime(num)

arr = []

p = []

not_p = []

# first I find all the numbers that num is divisible by

for i in (2..num/2)

if num % i == 0

arr << i

end

end # this should output [3, 9, 11, 33]

arr.each do |x| # I loop through each element in the above array

for i in (2..(x/2)) # I divide each element - x - by 2 because it cannot be divisble by anything greater than its half

if x % i == 0 # if x is divisble by i

not_p << i # I push the i into array#not_p

end # keep looping until i reaches x/2

end

if not_p.length == 0 # if there are no values in array#not_p, then I know x is a prime factor

p << x # so I push x into array#p

end

end

return p[-1] # returns the last element of the array, which is the largest

end

puts prime(99)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值