Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby | designing mathematics?

Tags:

math

ruby

primes

Situation:

  • I am writing a program to solve for primes. I need to solve problems to the tune of 4x^2+y^2=n, where n is a known variable.
  • Yes, it has to be Ruby.
  • I am comfortable with spending a lot of time on this project.
  • I would, preferably, like to write the solving algorithm for the equations myself and incorporate it as part of this project.

What I would really love:

  • If anyone can provide me with a link to a guide, website, or disambiguation regarding the construction of formal algorithms related specifically to solving algebraic equations, or provide me with information that seems to you the reader that it would help me in my quest.
  • Please don't suggest I use another language. I would also appreciate if, before answering, you accept that I really, really want to do this. There is no scope or time constraint on this project, and it is not for profit. It is for my own education.

Note:

  • I'm not directly opposed to implementing and using an already extant math library/module/something for Ruby, but the other way is preferable to me.

Closing comments:

The problem is that I know how to solve these equations by hand/with a calculator, but I'm not sure how to solve them in code.

like image 428
gal Avatar asked May 08 '12 09:05

gal


2 Answers

As it seems you are trying to implement the Sieve of Atkin then you are also probably aware that 4x^2+y^2=n is only the first of three equations. I don't want to spoil your fun and thus the below only implements that one. If you get stuck, just comment this answer and I will get back to you.

max = 100
primes = Array.new(max + 1) { false }
sqrt = Math.sqrt(max)
1.upto(sqrt) do |x|
  1.upto(sqrt) do |y|
    n = 4 * x**2 + y**2
    primes[n] ^= true if n <= max && (n % 12 == 1 || n % 12 == 5)
  end
end
like image 196
Jonas Elfström Avatar answered Sep 28 '22 08:09

Jonas Elfström


I suppose you are implementing the Sieve of Atkin. In that case, you don't actually solve the equation. Look at the original paper for the actual algorithm.

like image 28
user448810 Avatar answered Sep 28 '22 07:09

user448810