Problem solution · Turing

CCC 1996 P1 - Perfect Numbers

CCC 1996 P1 - Perfect Numbers: a Turing 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
55 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 1996 P1 - Perfect 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

  • 55 lines of Turing from the credited upstream file ccc96s1.t.
  • 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 1996 P1 - Perfect Numbers · TuringTuring
Use this to learn the idea, then write your own version.
% CCC 1996% problem 1: Deficient, Perfect and Abundant Numbers%% a perfect number = the sum of its proper divisors (1 thru < n)% a Deficent number < the sum of its proper divisors (1 thru < n)% an Abundant number > the sum of its proper divisors (1 thru < n) % file handling is used, the number of numbers is given% the numbers will be between 1 and 32500. function sumFactors (x : int) : int    var sum : int    sum := 0    for f : 1 .. x - 1        if x mod f = 0 then            sum := sum + f        end if    end for    result sumend sumFactors var infile : string := "dpa.in"var outfile : string := "dpa.out"var fi, fo : intvar n : intvar x : intvar sum : int open : fi, infile, getopen : fo, outfile, put get : fi, nfor i : 1 .. n    get : fi, x    sum := sumFactors (x)    if sum < x then        put x, " is a deficient number."        put : fo, x, " is a deficient number."    elsif x = sum then        put x, " is a perfect number."        put : fo, x, " is a perfect number."    else        put x, " is an abundant number."        put : fo, x, " is an abundant number."    end ifend for close : ficlose : fo      

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 ↗