Skip to content

Instantly share code, notes, and snippets.

@ellismarte
Created March 28, 2016 22:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ellismarte/07e727ebf56b57ebce5b to your computer and use it in GitHub Desktop.
Save ellismarte/07e727ebf56b57ebce5b to your computer and use it in GitHub Desktop.
def is_prime?(n)
if n == 1 || n == 2 || n == 3
return true
end
counter = 4
while counter < n do
if n % counter == 0
return false
end
counter += 1
end
return true
end
def is_happy?(n)
p "is happy #{n}"
processed_nums = {}
sum = 0
response = square_and_sum(n)
while !processed_nums[response] do
if response == true
return true
else
processed_nums[response] = true
response = square_and_sum(response)
end
end
return false
end
def square_and_sum(n)
sum = 0
n.to_s.split("").each do |i|
sum += (i.to_i * i.to_i)
end
if sum == 1
return true
else
return sum
end
end
def happy_primes(start_from, end_at)
all_happy_primes = []
n = end_at - start_from
n.times do |num|
num = num + start_from + 1
if num == 0
next
end
if is_prime?(num)
if is_happy?(num)
all_happy_primes << num
end
end
end
return all_happy_primes
end
p happy_primes(0,50)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment