0% found this document useful (0 votes)
9 views12 pages

Prime Number Check with Nested Loops

The document describes a Python program that checks for prime numbers between 2 and 49 using nested loops. It explains the logic behind the code, including how it determines if a number is prime by checking for divisibility. Additionally, it discusses potential optimizations for the program and provides examples of summing various types of series without using user-defined functions.

Uploaded by

anand325819
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views12 pages

Prime Number Check with Nested Loops

The document describes a Python program that checks for prime numbers between 2 and 49 using nested loops. It explains the logic behind the code, including how it determines if a number is prime by checking for divisibility. Additionally, it discusses potential optimizations for the program and provides examples of summing various types of series without using user-defined functions.

Uploaded by

anand325819
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

This Python program is checking for prime numbers in the range from 2 to 49.

The program uses a


combination of a for loop and a while loop to determine whether each number i in the range is
prime or not.
Let's break it down step by step:

Code Breakdown:
num = 2
for i in range(2, 50): # Loop through numbers from 2 to 49
j = 2
while (j <= (i / 2)): # Check potential divisors from 2 to i/2
if (i % j == 0): # If i is divisible by j
break # i is not prime, so break the loop
j += 1 # Try the next divisor (increment j)
if (j > i / j): # If j exceeds i / j, it means i is prime
print(i) # Print i if it's prime

Explanation:
1. Variable Initialization:
• num = 2: This seems unnecessary because it's not used later in the code.

2. Outer Loop (for i in range(2, 50)):

• This loop iterates through numbers from 2 to 49. Each number i is being checked
whether it is prime or not.
3. Inner Loop (while (j <= (i / 2))):

• For each number i, the inner loop checks if there exists any number j (starting from
2) that divides i without leaving a remainder.

• If such a divisor j is found (i.e., i % j == 0), then i is not a prime number, and
the loop is broken (break).

4. Incrementing j:

• If j does not divide i, then j is incremented (j += 1), and the program checks the
next number for divisibility.
5. Prime Number Check (if (j > i / j)):

• After the while loop finishes, if j becomes greater than i / j, it means that i has
no divisors less than or equal to its square root, indicating that i is a prime number.

• This is based on the fact that if a number has a divisor larger than its square
root, the corresponding divisor must be smaller than the square root (so we
only need to check divisors up to sqrt(i)).

• If this condition holds true, i is prime, and it is printed (print(i)).

Example Walkthrough:
Let's walk through the first few iterations to see how it works for numbers like 2, 3, 4, 5:
• i = 2:
• The while loop runs checking divisibility starting from j = 2.

• Since i / 2 = 1, the loop doesn't run as the condition j <= i / 2 is not


satisfied.
• The condition j > i / j (i.e., 2 > 2 / 2 → 2 > 1) holds true, so 2 is prime
and is printed.
• i = 3:
• The while loop runs with j = 2.

• 3 is not divisible by 2 (3 % 2 != 0), so j is incremented to 3, which breaks the


loop.
• The condition j > i / j (i.e., 3 > 3 / 3 → 3 > 1) holds true, so 3 is prime
and is printed.
• i = 4:
• The while loop starts with j = 2.

• 4 is divisible by 2 (4 % 2 == 0), so the loop breaks early.

• Since the loop is broken, 4 is not prime, and it is not printed.

• i = 5:
• The while loop starts with j = 2.

• 5 is not divisible by 2 (5 % 2 != 0), so j is incremented.

• The while loop continues checking j = 3, but it stops as j > i / j.

• The condition j > i / j (i.e., 3 > 5 / 3 → 3 > 1.67) holds true, so 5 is


prime and is printed.

Optimizations:
The program could be optimized by:
• Only checking divisors up to sqrt(i): Instead of checking up to i/2, we only need to
check up to the square root of i, because factors greater than sqrt(i) would have already
been found in the lower range.
• Skipping even numbers: After checking 2, you could skip all other even numbers (i % 2
== 0), as they are not prime.


# Print all prime numbers between 2 and 50

for num in range(2, 51): # Loop through numbers from 2 to 50


for i in range(2, num): # Check divisors from 2 to (num - 1)
if num % i == 0: # If divisible, not a prime
break
else:
# This else belongs to the for-loop, not the if-statement.
# It runs only if the loop was NOT broken (meaning no divisor was found)
print(num)
🧠 Explanation Step-by-Step:
for num in range(2, 51):

We loop through all numbers from 2 to 50 (since 1 is not prime).

Inner loop: for i in range(2, num):

For each number num, we check all smaller numbers (i) to see if they divide num.

if num % i == 0:

If num is divisible by i (remainder 0), then num is not prime.

We use break to stop checking further since we already know it’s not prime.

else: (paired with the inner for loop)

The else part runs only if the for loop didn’t break — that means we found no divisors, so the
number is prime.

print(num)

Print the number if it’s prime.

🧩 Output:
Copy code
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
⚡ Simplified Explanation:
The outer loop picks a number.

The inner loop tries to divide it by smaller numbers.

If any number divides it exactly → not prime, so break.


If no number divides it → prime, so print it.

for num in range(2, 51): # Outer loop for numbers 2 to 50


j = 2 # Start checking from 2
while j <= num / 2: # Only check divisors up to half the number
if num % j == 0: # If divisible, not a prime
break
j += 1 # Move to next possible divisor
else:
# This else runs only if the while loop is NOT broken (means no divisor found)
print(num)
🧠 Step-by-Step Explanation:
for num in range(2, 51):

The outer for loop picks numbers from 2 to 50 (since 1 is not prime).

j=2

We start checking divisibility from 2, because every number is divisible by 1.

while j <= num / 2:

We check possible divisors up to half of the number (num/2).


(If a number has a factor larger than half, the smaller pair factor would already be found.)

if num % j == 0:

If the remainder is 0, it means num is divisible by j, so it’s not prime.

The break statement stops the while loop.

j += 1

If not divisible, move to the next number (j = j + 1).

else: (attached to while)

This else runs only when the while loop finishes normally (i.e., no break happened).

That means no divisors were found → the number is prime, so print it.

🧩 Output:
Copy code
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
⚡ In Simple Words:
The for loop goes through each number.

The while loop checks if it has any divisors.

If none are found → it’s prime → print it.

Example 1: Summing the first n integers


n = 10 # You can change n to any integer
total_sum = 0
for i in range(1, n + 1):
total_sum += i

print(f"Summation of the series 1 + 2 + ... + {n} is: {total_sum}")

Explanation:
• n = 10: We're setting the number of terms in the series. In this case, it's 10.

• total_sum = 0: This is where we initialize the sum to zero. We'll keep adding the terms
of the series to this variable.
• for i in range(1, n + 1): This is the loop. It starts from i = 1 and runs until i
= 10 (because range(1, n + 1) generates values from 1 to n inclusive). On each
iteration, i will take the value of the next integer.

• total_sum += i: For each value of i, we add it to total_sum. This means we


accumulate the sum of all the numbers from 1 to n.
• print(f"Summation of the series 1 + 2 + ... + {n} is:
{total_sum}"): Finally, we print the result. After the loop finishes, total_sum holds
the sum of all integers from 1 to n.

Result: For n = 10, the program will calculate 1 + 2 + 3 + ... + 10 = 55 and print it.

Example 2: Summing the first n terms of an arithmetic series


a = 1 # First term
d = 1 # Common difference
n = 10 # Number of terms

total_sum = 0
for i in range(n):
total_sum += a + i * d

print(f"Summation of the arithmetic series is: {total_sum}")

Explanation:
• a = 1: This is the first term of the arithmetic series.

• d = 1: This is the common difference between consecutive terms. Each term is d units
larger than the previous one.
• n = 10: This is the number of terms you want to sum up in the series.

• total_sum = 0: Again, we initialize the sum to zero.

• for i in range(n): This loop runs n times, where i takes values from 0 to n-1. For
each i, we compute the value of the i-th term.

• a + i * d: The formula to get the i-th term of an arithmetic series is a + i * d. We


calculate each term and add it to total_sum.

• total_sum += a + i * d: This line adds the calculated term to total_sum.

• print(f"Summation of the arithmetic series is: {total_sum}"):


Finally, we print the result.
For a = 1, d = 1, and n = 10, the arithmetic series is 1, 2, 3, ..., 10. The sum is 55.

Example 3: Summing the first n terms of a geometric series


a = 1 # First term
r = 2 # Common ratio
n = 10 # Number of terms

total_sum = 0
for i in range(n):
total_sum += a * r**i

print(f"Summation of the geometric series is: {total_sum}")

Explanation:
• a = 1: This is the first term of the geometric series.

• r = 2: This is the common ratio. Each term in the series is obtained by multiplying the
previous term by r.

• n = 10: This is the number of terms you want to sum up.

• total_sum = 0: Again, we initialize the sum to zero.

• for i in range(n): This loop runs n times, and i takes values from 0 to n-1.
• a * r**i: The formula for the i-th term of a geometric series is a * r**i, where **
represents exponentiation. In each iteration, the term a * r**i is calculated and added to
total_sum.

• total_sum += a * r**i: This line adds the calculated term to total_sum.

• print(f"Summation of the geometric series is: {total_sum}"):


Finally, we print the result.
For a = 1, r = 2, and n = 10, the geometric series is 1, 2, 4, 8, 16, 32, 64,
128, 256, 512. The sum is 1023.

Example 4: Summing the squares of the first n integers


n = 10
total_sum = 0
for i in range(1, n + 1):
total_sum += i**2

print(f"Sum of squares of the first {n} integers is: {total_sum}")

Explanation:
• n = 10: This is the number of terms you want to consider.

• total_sum = 0: Initialize the sum to zero.

• for i in range(1, n + 1): The loop runs from i = 1 to i = 10.

• i**2: In this case, we are summing the squares of the integers, so for each i, we calculate
i**2 (i.e., i raised to the power of 2).

• total_sum += i**2: Add each squared value to total_sum.


• print(f"Sum of squares of the first {n} integers is:
{total_sum}"): Finally, print the result.

For n = 10, the series of squares is 1^2 + 2^2 + 3^2 + ... + 10^2, and the sum is
385.

Example 5: Using sum() with a list comprehension (no explicit loop)


n = 10
total_sum = sum(i**2 for i in range(1, n + 1))

print(f"Sum of squares of the first {n} integers is: {total_sum}")

Explanation:
• n = 10: This is the number of terms.
• sum(i**2 for i in range(1, n + 1)): This is a more compact version of the
previous example. It uses the sum() function with a generator expression. The generator
expression i**2 for i in range(1, n + 1) generates the squares of the numbers
from 1 to n. The sum() function adds them up.
• print(f"Sum of squares of the first {n} integers is:
{total_sum}"): Finally, print the result.

This method does the same thing as the previous loop example but is more concise.

Summary:
• For loops: Used to iterate over a range of values and accumulate the sum.
• sum() function: A built-in function that can be used with a generator expression for a
cleaner approach.
• Arithmetic series: The i-th term is calculated as a + i * d, where a is the first term and
d is the common difference.

• Geometric series: The i-th term is a * r**i, where r is the common ratio.

• Squaring integers: For summing squares, you calculate i**2 for each i and add it up.

Let me know if you'd like further clarification on any part!

You said:
summation of series, in python without user defined functions with explanation in python
ChatGPT said:

To calculate the summation of a series in Python without defining user functions, you can use a
simple loop or even Python's built-in sum() function with a list comprehension or generator
expression.
Here, I'll explain a few types of series and how to calculate their sum directly in Python, with an
emphasis on not using user-defined functions.

Example 1: Summing the first n integers (e.g., 1 + 2 + 3 + ... + n)


In this case, we are summing all the integers from 1 to n.

Code:
n = 10 # You can change n to any positive integer
total_sum = 0 # Initialize total sum to 0

# Loop to add the first n integers


for i in range(1, n + 1): # range starts at 1 and goes to n inclusive
total_sum += i # Add the current value of i to total_sum

# Output the result


print(f"Summation of the series 1 + 2 + ... + {n} is: {total_sum}")
Explanation:
1. n = 10: This sets the number of terms you want to sum, from 1 to n (in this case, 10).

2. total_sum = 0: We initialize the variable total_sum to store the sum of the series.

3. for i in range(1, n + 1): This loop starts at 1 and goes up to n. Each iteration
adds i to total_sum.

4. total_sum += i: This line adds the value of i to total_sum in each loop iteration.

5. print(f"Summation of the series 1 + 2 + ... + {n} is:


{total_sum}"): After the loop finishes, we print the total sum.

Result:
For n = 10, this will output:
Summation of the series 1 + 2 + ... + 10 is: 55

Example 2: Summing the first n terms of an arithmetic series (e.g., 1, 3, 5, 7, ...)


For an arithmetic series, the terms increase by a constant difference (d) between consecutive terms.
For example, 1, 3, 5, 7, ... has a common difference of 2.

The n-th term of an arithmetic series is given by:

Tn=a+(n−1)⋅d
where a is the first term, and d is the common difference.

Code:
a = 1 # First term
d = 2 # Common difference
n = 10 # Number of terms

total_sum = 0 # Initialize the total sum

# Loop to sum the first n terms of the arithmetic series


for i in range(n):
total_sum += a + i * d # Calculate the i-th term and add it to total_sum

# Output the result


print(f"Summation of the arithmetic series 1 + 3 + 5 + ... is: {total_sum}")

Explanation:
1. a = 1: First term of the series (in this case, it's 1).

2. d = 2: Common difference between consecutive terms.

3. n = 10: We want the sum of the first 10 terms.

4. total_sum = 0: Initialize the sum to zero.


5. for i in range(n): This loop runs n times. For each i, it calculates the i-th term
using the formula a + i * d and adds it to total_sum.

6. total_sum += a + i * d: The i-th term is added to total_sum.

7. print(f"Summation of the arithmetic series ..."): Finally, print the


total sum.
Result:
For a = 1, d = 2, and n = 10, the arithmetic series is 1, 3, 5, 7, ..., 19. The sum
is:
Summation of the arithmetic series 1 + 3 + 5 + ... is: 100

Example 3: Summing the first n terms of a geometric series (e.g., 1, 2, 4, 8, ...)


In a geometric series, each term is found by multiplying the previous term by a constant ratio r.

The n-th term of a geometric series is given by:

Tn=a⋅r(n−1)
where a is the first term, and r is the common ratio.

Code:
a = 1 # First term
r = 2 # Common ratio
n = 10 # Number of terms

total_sum = 0 # Initialize total sum

# Loop to sum the first n terms of the geometric series


for i in range(n):
total_sum += a * r**i # Calculate the i-th term (a * r^i) and add to
total_sum

# Output the result


print(f"Summation of the geometric series 1 + 2 + 4 + ... is: {total_sum}")

Explanation:
1. a = 1: First term of the geometric series (1).

2. r = 2: Common ratio (each term is twice the previous one).

3. n = 10: We want the sum of the first 10 terms.

4. total_sum = 0: Initialize the total sum to zero.

5. for i in range(n): This loop iterates n times, and for each iteration, calculates the i-
th term using the formula a * r**i.

6. total_sum += a * r**i: The i-th term is added to the total sum.


7. print(f"Summation of the geometric series ..."): Finally, we print the
total sum.
Result:
For a = 1, r = 2, and n = 10, the geometric series is 1, 2, 4, 8, ..., 512. The sum
is:
Summation of the geometric series 1 + 2 + 4 + ... is: 1023

Example 4: Summing the squares of the first n integers (e.g., 1² + 2² + 3² + ...)


To compute the sum of squares, you square each number and then add it to the sum.

Code:
n = 10 # You can change n to any positive integer
total_sum = 0 # Initialize total sum

# Loop to add the squares of the first n integers


for i in range(1, n + 1):
total_sum += i**2 # Add the square of i to total_sum

# Output the result


print(f"Sum of squares of the first {n} integers is: {total_sum}")

Explanation:
1. n = 10: Number of terms.

2. total_sum = 0: Initialize total sum to zero.

3. for i in range(1, n + 1): This loop runs from i = 1 to i = n.

4. total_sum += i**2: Adds the square of i to total_sum.

5. print(f"Sum of squares of the first {n} integers is:


{total_sum}"): Finally, print the total sum of squares.

Result:
For n = 10, the sum of squares is 1² + 2² + 3² + ... + 10² = 385:
Sum of squares of the first 10 integers is: 385

Example 5: Using sum() with a generator expression (without explicit loops)


Instead of writing explicit loops, you can use a generator expression inside the sum() function
for more concise code.

Code:
n = 10
total_sum = sum(i**2 for i in range(1, n + 1)) # Summing squares using
generator expression
# Output the result
print(f"Sum of squares of the first {n} integers is: {total_sum}")

Explanation:
• sum(i**2 for i in range(1, n + 1)): This is a more compact form of the
loop. It generates the squares of the numbers from 1 to n and sums them.

• print(f"Sum of squares ..."): Finally, it prints the result.

You might also like