How to create a method that returns an n-dimensional number?

I am trying to write a method that returns an n-dimensional number.

I developed a solution, but the problem is in my method. I am creating a large array of numbers that seems to be processed very slowly. (1..104729).to_amore precisely. I chose 104729 because max ncan be 10000, and the 10000th number is 104729. I am looking for a way to optimize my method.

Is 104729 too much? Is there a way to write this so that I don't create a large array?

Here's the method:

def PrimeMover(num)

  def is_prime(x)
    i = 0
    nums = (2..x).to_a
    while nums[i] < nums.max
      if x % nums[i] != 0
        i += 1
      else
        return false
      end
    end
    return true
  end

  primes_arr = (3..104729).to_a.select {|y| is_prime(y)}

  primes_arr[num]

end
+4
source share
4 answers

You can use Ruby's built-in method#prime? , which seems pretty efficient.

The code:

require 'prime'
primes_arr = (3..104729).to_a.select &:prime?

2-3 , .

, . Ruby: http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Ruby

0
require "prime"

def find_prime(nth)
  Prime.take(nth).last
end
+9

Ruby lazy enumerator :

require 'prime'
(1...100_000).lazy.select(&:prime?).take(100).to_a

, :

Prime.take(100)
+5

is_prime, Prime:

- , 1 , 1 . , x - , x, 1. , 2, x - 1.

def prime?(x)
  return false if x < 2
  2.upto(x - 1) do |n|
    return false if (x % n).zero?
  end
  true
end

As soon as it x % nhas a remainder, we can break the cycle and say that this number is not prime. This will save you from cycling throughout the range. If all possible numbers have been exhausted, we know that the number is prime.

This is not yet optimal. To do this, you will need sieve or another detection algorithm for trial division. But this is a big improvement to your code. Taking the nth up to you.

+1
source

Source: https://habr.com/ru/post/1568299/


All Articles