Geeky Minds

Innovation, Inspiration, Instigation

Oct 15, 2017 - 2 minute read - Comments - Problem Solving Ruby

Solving Project Euler Problem 13 – Large Sum

For my next problem, I decided to take one of the popular routes and experimented with few of the simpler problems from Project Euler

The first problem that I tried was Problem 13 – Large Sum

Problem Statement

Work out the first ten digits of the sum of N 50-digit numbers.

Input Format

The first line contains N, next N lines contain a 50 digit number each.

Output Format

Print only first 10 digits of the final sum


1 ≤ N ≤ 10^3

Sample Input


Sample Output


When I started this originally, I was a bit confused and I was approaching it wrongly.

I thought I’m supposed to find the sum of digits of all numbers combined together, then print the first 10 digits of it. Naturally, it was completely wrong, and I realized it after few failed submissions (Boo to the late night/early morning mindset which confuses you)

Read the problem statement carefully. It’s not about adding the digits of the numbers. It’s about adding the numbers themselves, be it 5 or 50 or 500 numbers, and finally printing only the first 10 digits of the sum. Each number, of course, would be 50 digits long.

Without further ado, here’s my solution:

    inputs = STDIN.readline().chomp.to_i
    val = 0
    loop do
      n = STDIN.readline().to_i
      val = val + n
      inputs = inputs - 1
      break if inputs == 0
    array = val.to_s.split('')
    print "#{array[0..9].join('').to_i}"

Breakdown of the solution:

  • Read the number of test cases from STDIN as an integer
  • Initiate the final value for our calculation
  • Loop over the test cases
  • Read the set of numbers (1 on each line, 1 for each test case) and keep adding them iteratively for our val
  • Once the final val is present, store it in an array, splitting each digit of the final sum into individual array elements
    • The elements would be stored as char/string in this case, as the .split() method in Ruby works on string
  • Print the final value, taking only the first 10 elements of the array and converting them to Integer again.

That’s it, folks! I’ll be writing more about other problems I solve as and when they happen 🙂

Note: Solution files for this and any future Project Euler problems that I solve can be found here: Github: glnarayanan/ProjectEuler

Tags: Hackerrank Problem Solving Project Euler Ruby

comments powered by Disqus