Project Euler Problem #112

Problem #112 concerns numbers which are neither increasing nor decreasing. The question reads:

Project Euler Problem 112: Bouncy numbers
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.

My solution for this question can be summarized as a brute force approach that relies on the percentage being an integer. Here’s my solution:

Solution #1: Brute Force Approach

We simply check every interval of 100 consecutive positive integers until the cumulative total of bouncy numbers is 99% of the cumulative total of the number of integers in all of the intervals. Here is an implementation of this approach in Python 2.7:

 '''
 Author: ArrGeeStee
 Brute Force Approach to Project Euler Problem #112
 '''
 
 import time
 
 def isBouncy(n):
     a = str(n)
     curr = int(a[0])
     increasing = True
     decreasing = True
     for c in range(1,len(a)):
         v = int(a[c])
         if(v>curr):
             decreasing = False
         if(v<curr):
             increasing = False
         if not decreasing and not increasing:
             return True
         curr = v
     return False

 def projectEulerProblemOneHundredTwelve(n):
     complement = 100-n
     notBouncy = 100
     total = 100
     while(complement*total!=notBouncy*100):
         total+=100
         for x in range(100):
             if not isBouncy(total-x):
                 notBouncy+=1
     return total
 
 start = time.time()
 print projectEulerProblemOneHundredTwelve(99)
 print ("--- %s seconds ---" % (time.time()-start))
 
 '''
 Prints
 
 1587000
 --- 2.88207697868 seconds ---
 
 for input of n = 99.
 ''' 

And with that, we’re done. This brute force approach wasn’t very efficient as it took nearly 3 seconds to run. I may come back to this problem at some point to search for a more efficient solution.

Thanks for reading! See you tomorrow.

Published by Walker Kroubalkian

My name is Walker Kroubalkian. I really enjoy math, computer science, and hiking.

Leave a comment

Design a site like this with WordPress.com
Get started