Skip to content

Instantly share code, notes, and snippets.

@alfo
Created December 10, 2014 19:36
Show Gist options
  • Save alfo/4a66f04a4dd6a0372d9a to your computer and use it in GitHub Desktop.
Save alfo/4a66f04a4dd6a0372d9a to your computer and use it in GitHub Desktop.
Multiply two huge numbers together without Ruby's help
first_string = gets.chomp
second_string = gets.chomp
to_find = gets.chomp
def string_times_int(string, int)
product = ""
carry = 0
loop = string.length - 1
while loop >= 0 or carry != 0
if loop >= 0
from_string = string[loop]
else
from_string = 0
end
this_number = from_string.to_i * int + carry
carry = this_number / 10
product += (this_number % 10).to_s;
loop = loop - 1
end
product.reverse
end
def string_add_string(a, b)
if a.length > b.length
first = a
second = b
else
first = b
second = a
end
sum = ""
carry = 0
loop = first.length - 1
while loop >= 0 or carry != 0
if loop >= 0
first_from_string = first[loop]
else
first_from_string = 0
end
second_index = loop - (first.length - second.length)
if second_index >= 0
second_from_string = second[second_index]
else
second_from_string = 0
end
this_number = first_from_string.to_i + second_from_string.to_i + carry
carry = this_number / 10
sum += (this_number % 10).to_s
loop -= 1
end
sum.reverse
end
total_sum = "0"
loop = first_string.length - 1
while loop >= 0
reverse_index = first_string.length - 1 - loop
the_number = first_string[loop].to_i
addition = string_times_int(second_string, the_number)
reverse_index.times do
addition += "0"
end
total_sum = string_add_string(total_sum, addition)
loop -= 1
end
found_count = 0
total_sum.each_char do |char|
found_count += 1 if char == to_find
end
puts "Product was #{total_sum}"
puts "Found #{found_count} instances of #{to_find}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment