Exercise Overview
This exercise demonstrates how to use loops to solve mathematical problems. We’ll create a program that finds and prints:- Prime numbers
- Odd numbers
- Multiples of 7
Problem Statement
Create a program that prints the following within the range of 100 to 150:Prime Numbers
Numbers divisible only by 1 and themselves
Odd Numbers
Numbers not divisible by 2
Multiples of 7
Numbers divisible by 7
Solution
Finding Prime Numbers
To find prime numbers, we use a nested loop to check if a number has any divisors:How the prime number algorithm works
How the prime number algorithm works
1
Iterate through the range
The outer loop goes from 100 to 150
2
Check for divisors
The inner loop tests if the number is divisible by any number from 2 to i-1
3
Count divisors
If we find a divisor, increment the counter
4
Determine if prime
If the counter is 0, the number has no divisors and is therefore prime
Finding Odd Numbers
For odd numbers, we can start at 101 and increment by 2:By starting at 101 (an odd number) and incrementing by 2, we skip all even numbers automatically. This is much more efficient than checking each number.
Finding Multiples of 7
For multiples of 7, we use the modulo operator:Complete Program
Key Concepts
For Loops
Used to iterate over a range of numbers
Nested Loops
A loop inside another loop, useful for complex algorithms
Modulo Operator
% returns the remainder of a divisionLoop Optimization
Using
i += 2 skips unnecessary iterationsPractice Challenges
Challenge 1: Extend the range
Challenge 1: Extend the range
Modify the program to work with a range of 1 to 1000. What optimizations could you make to the prime number algorithm?
Challenge 2: Even numbers
Challenge 2: Even numbers
Add a section to print all even numbers in the range.
Challenge 3: Perfect squares
Challenge 3: Perfect squares
Add a section to print all perfect squares (4, 9, 16, 25, etc.) in the range.