Problem solution · Python

CCC 2009 S1 - Cool Numbers

CCC 2009 S1 - Cool Numbers: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to CCCSolutions.

Technique
Direct simulation
Source
CCCSolutions
Length
34 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For CCC 2009 S1 - Cool Numbers, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 34 lines of Python from the credited upstream file ccc09s1.py.
  • The implementation keeps its working state in language-native values and containers.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from CCCSolutions by CCCSolutions contributors · Milliken Mills High School and is used under the MIT licence.

Full codeCCC 2009 S1 - Cool Numbers · PythonPython
Use this to learn the idea, then write your own version.
# CCC 2009## S1: Cool Numbers## This is a FASTER method still.# by Goutam Venkatramanan## If x = a^3 and x = b^2 then a^3 = b^2 or a^3/b^2 = 1## That means that if a could be factored into n*m you'd have# n*m*n*m*n*m/b*b = 1. But wait a minute.... that doesn't work.# There is no way to factor b to cancel the 3 m's and 3 n's....# Nope, the only way is if a factors into n*n and b into n*n*n## so that means x = n^6.  QED## SO this problem means: find all the numbers^6 that are in the range# up to 100,000,000## Goutram's insight was that there are very few of these, in fact# n = 22 means n^6 = 113,379,905,# so 21 is the max number you need to test. file = open("s1.5.in", "r")a = int(file.readline())b = int(file.readline())count = 0for n in range(1,22):    i = n**6    if (i >= a) and (i <= b):        count+=1print count  

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗