Understanding this Ruby Program to find prime numbers

烂漫一生 提交于 2019-12-24 19:15:11

问题


I am new to Ruby, and I have been reading over this program that finds us prime numbers.

This example came in a textbook, after talking about loops (while & until) it showed this example.

I find it pretty confusing. What is the purpose of the prime_flag? Why is J set as 2?

(j <= i / 2) -- This one I don't understand.

j = j + 1 -- what is the purpose of this.

My apologies for the long question, but any help is greatly appreciated. Please and thank you.

# Initialize our counter
i = 1

# i: [0, 100]
while (i <= 100)
  # Initialize prime flag 
  prime_flag = true
  j = 2
  # Test divisibility of i from [0, i/2]
  while (j <= i / 2)
    # puts " i ==> " to i.to_s + " j ==> " + j.to_s 
    if (i % j == 0)
      prime_flag = false
      # break
    end 
    j = j + 1
  end
  # We found a prime!
  if prime_flag
    puts "Prime ==> " + i.to_s"
  end 
  # Increment the counter
  i += 1
end

回答1:


The while loop is counting from 2 to half of i and testing to see if it is prime.

Why is J set as 2?

A prime number is a number that has no factors aside from one and itself. If j started at 1, of course 1 is a factor of the number. If we included 1, then the code would think none of the numbers are prime because it would consider 1 a factor.

(j <= i / 2)

The while loop checks up to half of the number. Technically, you only need to check up to the square root of the number.

j = j + 1 -- what is the purpose of this.

We need to increment j to move on the the next number. The program is essentially doing something like:

  1. Start with j at 2.
  2. Is i divisible by j?
    1. Yes? Clear the prime flag.
  3. Set j to the next number, 3.
  4. Is i divisible by j?
    1. Yes? Clear the prime flag.
  5. Repeat up to half of i

In the example you posted, break is commented out, and I'm not sure why. The break would be a good thing to do. That basically says, "OK, we found a factor for i, we don't need to keep looping looking for more factors.

What is the purpose of the prime_flag?

The prime_flag is being used to track if it has found any factors for i. The variable starts off as true, so "Yes", assume the number is prime. As soon as we find a factor, it sets it to false, indicating that i is not prime.



来源:https://stackoverflow.com/questions/49713404/understanding-this-ruby-program-to-find-prime-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!