Lab: Odd Integers
In this lab, you will develop a program that writes odd integers as the difference between two squares of integers.
Instructions
You should complete this lab individually.
Background
Every odd integer is equal to the difference between the squares of two integers. For example:
1=1−0=12−02 3=4−1=22−12 5=9−4=32−22 7=16−9=42−32
In class, we proved this with a constructive proof. Our proof includes an algorithm to write any odd integer as the difference between two squares of integers.
Note: If you are unfamiliar with the algorithm, review Theorem 2.4 in the textbook.
Step 1: Manual Calculation
Form the difference between squares for several odd integers using a pencil, paper, and simple calculator.
- 9
- 23
- 201
Step 2: Python Program
You should develop a Python program to write odd integers as the difference between two squares of integers. Name your program odd.py
. The program should accept one argument, an odd integer. The program should print the associated integers, separated by line breaks. For example:
> python odd.py 1
1
0
> python odd.py 7
4
3
Step 3: Edge Cases
Ensure your program works for negative odd integers.
Also, your program should exit with an error message and a non-zero exit code if an invalid argument is supplied. For example:
> python odd.py 2
odd.py: error: argument odd_integer: 2 is not odd.
> python odd.py 3.14
odd.py: error: argument odd_integer: 3.14 is not an integer.
Hint: I recommend using Python’s argparse
module to validate command-line arguments.
Submit
Upload odd.py
to Gradescope.
Learning Goals
- Implement algorithms as code
- Implement error handling