سؤال

I made a method that generates prime factors. Whatever composite number I push to it, it gives the prime factors. However, if I push a prime number into it, it wouldn't return 1 and the number itself. Instead, it would return 1 and some prime number smaller than the number pushed into the method.

I decided to shove an if statement that would cut the process short if the number pushed into turns out to be prime. Here's the code:

def get_prime_factors(number)
  prime_factors = []
  i = 0
  primes = primes_gen(number)
  if primes.include?(number)
    return "Already a prime!"
  end
  original_number = number
  while primes[i] <= original_number / 2
    if number % primes[i] == 0
      prime_factors << primes[i]
      number = number / primes[i]
    else
      i = i + 1
    end
    if number == 1
      return prime_factors
    end
  end
end

I fed 101 to the method and the method returned nil. This method calls the primes_gen method, which returns an array containing all primes smaller than the input value. Here it is:

def primes_gen(limit)
  primes = []
  i = 0
  while i <= limit
    primes << i if isprime?(i)
    i = i + 1
  end
  primes.delete(0)
  primes.delete(1)
  return primes
end

I know there ought to be a more finessed way to fix the. If anyone wants to recommend a direction for me to explore as far as that goes, I'd be very grateful.

EDIT: Changed line 4 of the primes_gen() method to include a <= operator instead of a < operator.

هل كانت مفيدة؟

المحلول

Try changing primes = primes_gen(number) to primes = primes_gen(number+1) in first function and see if it works. Or try changing the i < limit condition to i <= limit in the second function.

Also, why are you deleting the 0th and 1st element in primes_gen method? Is it because of values you get for 0, 1? In which case, you can initialize with i=2.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top