【光子AI / Photon.AI】FreeManus 写代码能力测试
这篇文章摘要可以总结为: 一个Python编程任务,要求实现以下功能: 定义判断素数的函数 找出1到50之间的所有素数 计算这些素数的和 执行代码并显示结果 解决方案提供了两种实现方式: 使用FreeManus生成的优化算法,采用跳过偶数和3的倍数的优化策略 直接使用LLM推理模型的标准实现方法 两种方法都正确找出了1-50之间的15个素数(2,3,5...47),并计算出总和为328。程序包含完
【光子AI / Photon.AI】FreeManus 写代码能力测试
文章目录
- 【光子AI / Photon.AI】FreeManus 写代码能力测试
- 任务
- FreeManus 执行结果
- ====================================
- Prime Numbers Between 1 and 50 - Program and Results
- 直接使用 LLM 推理模型的回复
- ============== Seed ======================
- ============== MiniMax======================
- ============== Manus======================
- ============== Kimi ======================
- =============== Ernie =====================
- =============== Claude =====================
- =============== Gemini=====================
- =============== XiaoMi=====================
- =============== DeepSeek=====================
- ================ Qwen====================
- ================ ChatGLM====================
- ================ ChatGPT ====================
任务
Create a Python program that:
1. Defines a function to check if a number is prime
2. Finds all prime numbers between 1 and 50
3. Calculates the sum of these prime numbers
4. Execute the code and show the results
"""
Coding Demo - Programming task with verification
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from freemanus import FreeManus
from freemanus.utils.logger import console, print_divider
def main():
"""Run coding demo"""
print_divider("FreeManus Coding Demo")
agent = FreeManus(max_iterations=10)
# Coding task with multiple steps
result = agent.run("""
Create a Python program that:
1. Defines a function to check if a number is prime
2. Finds all prime numbers between 1 and 50
3. Calculates the sum of these prime numbers
4. Execute the code and show the results
""")
print_divider("Coding Demo Complete")
return result
if __name__ == "__main__":
main()
FreeManus 执行结果
====================================
Prime Numbers Between 1 and 50 - Program and Results
I have successfully created a Python program that meets all your requirements. Below is the complete solution, including the code, execution output, and a summary of the results.
📝 Complete Python Program
def is_prime_optimized(n):
"""
Check if a number is prime using optimized trial division.
Returns True if n is prime, False otherwise.
"""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
# Check divisibility up to sqrt(n)
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# Find all prime numbers between 1 and 50
primes = []
for num in range(1, 51):
if is_prime_optimized(num):
primes.append(num)
# Calculate the sum of prime numbers
prime_sum = sum(primes)
prime_count = len(primes)
# Display results
print(f"Primes between 1 and 50: {primes}")
print(f"Number of primes: {prime_count}")
print(f"Sum of primes: {prime_sum}")
🚀 Execution Results
When the program was executed, it produced the following output:
Primes between 1 and 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Number of primes: 15
Sum of primes: 328
📊 Summary of Results
| Metric | Value |
|---|---|
| Prime Numbers Found | 15 numbers |
| List of Primes | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 |
| Sum of Primes | 328 |
| Range Analyzed | 1 to 50 |
🔍 Key Features of the Solution
-
Efficient Prime Checking Function: The
is_prime_optimized()function uses an optimized trial division algorithm that:- Checks divisibility only up to the square root of the number
- Skips even numbers and multiples of 3 for efficiency
- Correctly handles edge cases (numbers ≤ 1, 2, and 3)
-
Complete Implementation: The program successfully:
- Defines the prime checking function as requested
- Finds all prime numbers between 1 and 50
- Calculates the sum of these prime numbers
- Executes the code and displays the results
-
Verification: The results have been verified and match known mathematical facts about prime numbers in this range.
💡 How to Use the Program
You can copy the code above and run it in any Python environment. The program will:
- Define the prime checking function
- Identify all prime numbers between 1 and 50
- Calculate and display their sum
- Show the count of prime numbers found
The solution is complete, efficient, and ready for use or further modification if needed.
直接使用 LLM 推理模型的回复
============== Seed ======================
Step 1: Understand Your Requirements
You need a Python program that defines a prime number checking function, finds all primes between 1 and 50, calculates their sum, and displays the results clearly.
Step 2: Complete Python Program
Here is a complete, well-commented program that meets all your requirements:
import math
# 1. Define a function to check if a number is prime
def is_prime(n):
"""
Check if a number is a prime number.
Args:
n (int): The number to check
Returns:
bool: True if n is prime, False otherwise
"""
# Prime numbers are greater than 1
if n <= 1:
return False
# 2 is the only even prime number
if n == 2:
return True
# Even numbers greater than 2 are not prime
if n % 2 == 0:
return False
# Check divisors from 3 up to square root of n (only odd numbers)
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
# 2. Find all prime numbers between 1 and 50
prime_numbers = []
for num in range(1, 51):
if is_prime(num):
prime_numbers.append(num)
# 3. Calculate the sum of these prime numbers
sum_of_primes = sum(prime_numbers)
# 4. Execute and show the results
print("Prime numbers between 1 and 50:")
print(prime_numbers)
print(f"\nSum of these prime numbers: {sum_of_primes}")
Step 3: Explanation of Key Parts
-
Prime Check Function (
is_prime):- First, it rejects numbers ≤ 1 (not prime by definition)
- Special case for 2 (the only even prime)
- Rejects all other even numbers (optimization to reduce checks)
- Only checks odd divisors up to the square root of
n(since factors larger than the square root would have a corresponding factor smaller than it)
-
Finding Primes 1-50:
- Iterates through numbers 1 to 50
- Uses
is_prime()to filter and collect primes into a list
-
Sum Calculation:
- Uses Python’s built-in
sum()function for efficient summation of the prime list
- Uses Python’s built-in
-
Output:
- Prints the list of primes and their total sum for clear visualization
Step 4: Expected Output
When you run this code, you will see:
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of these prime numbers: 328
Summary
- Prime Check Logic: The
is_primefunction uses mathematical optimizations (checking only up to square root, skipping even numbers) to efficiently determine primality. - Prime Collection: We iterate 1-50 and filter primes using our function, storing results in a list.
- Sum Calculation: The sum of primes 1-50 is 328, and the list of primes includes 15 numbers (2, 3, 5, …, 47).
============== MiniMax======================
I’ll create a Python program that checks for prime numbers, finds all primes between 1 and 50, and calculates their sum.
#!/usr/bin/env python3
"""
Prime Number Calculator
This program defines a function to check if a number is prime,
finds all prime numbers between 1 and 50,
and calculates their sum.
"""
def is_prime(n):
"""
Check if a number is prime.
Args:
n: The number to check
Returns:
True if n is prime, False otherwise
"""
# Prime numbers must be greater than 1
if n <= 1:
return False
# Check for factors from 2 to sqrt(n)
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def main():
"""Main function to find and sum prime numbers between 1 and 50."""
# Find all prime numbers between 1 and 50
prime_numbers = []
for num in range(1, 51):
if is_prime(num):
prime_numbers.append(num)
# Calculate the sum of prime numbers
prime_sum = sum(prime_numbers)
# Display the results
print("=" * 50)
print("Prime Numbers Calculator")
print("=" * 50)
print(f"\nPrime numbers between 1 and 50:")
print(f"{prime_numbers}")
print(f"\nTotal count of prime numbers: {len(prime_numbers)}")
print(f"Sum of prime numbers: {prime_sum}")
print("=" * 50)
if __name__ == "__main__":
main()
Now let me execute the program to show the results:
Python Prime Number Calculator - Results
I’ve created and executed a Python program that checks for prime numbers and calculates their sum. Here are the results:
Program Features:
- Prime checking function - Uses an efficient algorithm that checks divisibility up to √n
- Range search - Finds all prime numbers between 1 and 50
- Sum calculation - Computes the total of all prime numbers found
Results:
==================================================
Prime Numbers Calculator
==================================================
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Total count of prime numbers: 15
Sum of prime numbers: 328
==================================================
Summary:
- Prime numbers found: 15
- All primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
- Sum: 328
The program file has been saved at: /workspace/prime_calculator.py
============== Manus======================
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def main():
# Find all prime numbers between 1 and 50
primes = [n for n in range(1, 51) if is_prime(n)]
# Calculate the sum of these prime numbers
prime_sum = sum(primes)
# Print the results
print(f"Prime numbers between 1 and 50: {primes}")
print(f"Sum of these prime numbers: {prime_sum}")
if __name__ == "__main__":
main()

============== Kimi ======================
I’ll create a Python program that meets all your requirements. Let me write and execute the code for you:
def is_prime(n):
"""
Check if a number is prime.
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
"""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check odd divisors up to sqrt(n)
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# Find all prime numbers between 1 and 50
prime_numbers = []
for num in range(1, 51):
if is_prime(num):
prime_numbers.append(num)
# Calculate the sum of prime numbers
prime_sum = sum(prime_numbers)
# Display results
print("Prime numbers between 1 and 50:")
print(prime_numbers)
print(f"\nCount of prime numbers: {len(prime_numbers)}")
print(f"Sum of prime numbers: {prime_sum}")
# Let's also show the verification for a few numbers
print("\nVerification of prime numbers:")
for i in range(1, 11):
print(f"{i} is prime: {is_prime(i)}")
Results:
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Count of prime numbers: 15
Sum of prime numbers: 328
Verification of prime numbers:
1 is prime: False
2 is prime: True
3 is prime: True
4 is prime: False
5 is prime: True
6 is prime: False
7 is prime: True
8 is prime: False
9 is prime: False
10 is prime: False
Summary:
- Prime numbers found: 15 primes between 1 and 50
- Sum of primes: 328
- Algorithm used: Trial division up to √n for efficiency
The program successfully identifies all prime numbers in the specified range and calculates their sum. The is_prime() function efficiently checks primality by testing divisibility only up to the square root of the number.
=============== Ernie =====================
To solve this problem, we need to create a Python program that checks for prime numbers within a specified range, calculates their sum, and displays the results.
Approach
- Prime Check Function: Define a function
is_prime(n)that checks if a numbernis prime. A prime number is greater than 1 and has no divisors other than 1 and itself. - Find Primes in Range: Iterate through numbers from 1 to 50, using the
is_primefunction to identify all prime numbers in this range. - Sum Calculation: Sum all the identified prime numbers.
- Output Results: Print the list of prime numbers and their sum.
Solution Code
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [n for n in range(1, 51) if is_prime(n)]
total = sum(primes)
print("Prime numbers between 1 and 50 are:", primes)
print("Sum of prime numbers between 1 and 50 is:", total)
Explanation
- Prime Check Function: The
is_primefunction efficiently checks for primality by testing divisibility up to the square root of the number, reducing the number of checks needed. - List Comprehension: The list comprehension
[n for n in range(1, 51) if is_prime(n)]generates all prime numbers between 1 and 50 by applying theis_primefunction to each number in the range. - Sum Calculation: The
sumfunction calculates the total of all prime numbers in the list. - Output: The results are printed, showing the list of primes and their sum.
This approach ensures clarity and efficiency, leveraging mathematical optimizations for prime checking and Python’s built-in functions for concise and readable code.
=============== Claude =====================
Prime Numbers Program
I’ll create a Python program that finds all prime numbers between 1 and 50 and calculates their sum.
def is_prime(n):
"""
Check if a number is prime.
A prime number is a natural number greater than 1 that has no positive
divisors other than 1 and itself.
Args:
n: The number to check
Returns:
bool: True if the number is prime, False otherwise
"""
# Numbers less than 2 are not prime
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# Even numbers greater than 2 are not prime
if n % 2 == 0:
return False
# Check odd divisors from 3 to sqrt(n)
# We only need to check up to sqrt(n) because if n = a * b,
# one of them must be <= sqrt(n)
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def find_primes_in_range(start, end):
"""
Find all prime numbers within a given range.
Args:
start: Beginning of range (inclusive)
end: End of range (inclusive)
Returns:
list: All prime numbers in the range
"""
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
def main():
"""Main function to execute the prime number analysis."""
print("=" * 50)
print(" PRIME NUMBERS BETWEEN 1 AND 50")
print("=" * 50)
# Find all prime numbers between 1 and 50
prime_numbers = find_primes_in_range(1, 50)
# Display the prime numbers
print(f"\n📌 Prime numbers found: {len(prime_numbers)}")
print(f"\n📋 List of primes: {prime_numbers}")
# Calculate the sum
prime_sum = sum(prime_numbers)
# Display the sum
print(f"\n➕ Sum of all prime numbers: {prime_sum}")
# Additional visualization
print("\n" + "-" * 50)
print("Detailed breakdown:")
print("-" * 50)
# Show the addition
addition_str = " + ".join(map(str, prime_numbers))
print(f"\n{addition_str} = {prime_sum}")
# Show primes in a grid format
print("\n" + "-" * 50)
print("Prime numbers grid (1-50):")
print("-" * 50)
for i in range(1, 51):
if is_prime(i):
print(f"[{i:2d}]", end=" ")
else:
print(f" · ", end=" ")
if i % 10 == 0:
print() # New line every 10 numbers
# Execute the program
if __name__ == "__main__":
main()
Output Results:
==================================================
PRIME NUMBERS BETWEEN 1 AND 50
==================================================
📌 Prime numbers found: 15
📋 List of primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
➕ Sum of all prime numbers: 328
--------------------------------------------------
Detailed breakdown:
--------------------------------------------------
2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47 = 328
--------------------------------------------------
Prime numbers grid (1-50):
--------------------------------------------------
· [ 2] [ 3] · [ 5] · [ 7] · · ·
[11] · [13] · · · [17] · [19] ·
· · [23] · · · · · [29] ·
[31] · · · · · [37] · · ·
[41] · [43] · · · [47] · · ·
Summary:
| Metric | Value |
|---|---|
| Range | 1 to 50 |
| Prime Count | 15 |
| Prime Numbers | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 |
| Sum | 328 |
Python Program: Prime Numbers Between 1 and 50
Complete Code
def is_prime(n):
"""
Check if a number is prime.
A prime number is a natural number greater than 1
that has no positive divisors other than 1 and itself.
"""
# Numbers less than or equal to 1 are not prime
if n <= 1:
return False
# 2 is the only even prime number
if n == 2:
return True
# All other even numbers are not prime
if n % 2 == 0:
return False
# Check for odd divisors from 3 to square root of n
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# ============================================
# Main Program Execution
# ============================================
print("=" * 50)
print(" PRIME NUMBERS FINDER (1 to 50)")
print("=" * 50)
# Step 1: Find all prime numbers between 1 and 50
prime_numbers = []
print("\nChecking each number from 1 to 50...\n")
for num in range(1, 51):
if is_prime(num):
prime_numbers.append(num)
print(f" ✓ {num} is PRIME")
# Step 2: Display the results
print("\n" + "-" * 50)
print("RESULTS:")
print("-" * 50)
print(f"\n📋 All prime numbers between 1 and 50:")
print(f" {prime_numbers}")
# Step 3: Calculate and display the sum
prime_sum = sum(prime_numbers)
prime_count = len(prime_numbers)
print(f"\n📊 Statistics:")
print(f" • Total count of primes: {prime_count}")
print(f" • Sum of all primes: {prime_sum}")
# Bonus: Show the addition
print(f"\n📝 Calculation breakdown:")
print(f" {' + '.join(map(str, prime_numbers))}")
print(f" = {prime_sum}")
print("\n" + "=" * 50)
Output
==================================================
PRIME NUMBERS FINDER (1 to 50)
==================================================
Checking each number from 1 to 50...
✓ 2 is PRIME
✓ 3 is PRIME
✓ 5 is PRIME
✓ 7 is PRIME
✓ 11 is PRIME
✓ 13 is PRIME
✓ 17 is PRIME
✓ 19 is PRIME
✓ 23 is PRIME
✓ 29 is PRIME
✓ 31 is PRIME
✓ 37 is PRIME
✓ 41 is PRIME
✓ 43 is PRIME
✓ 47 is PRIME
--------------------------------------------------
RESULTS:
--------------------------------------------------
📋 All prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
📊 Statistics:
• Total count of primes: 15
• Sum of all primes: 328
📝 Calculation breakdown:
2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47
= 328
==================================================
Summary
| Item | Value |
|---|---|
| Range | 1 to 50 |
| Prime Numbers Found | 15 |
| Prime Numbers | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 |
| Sum of Primes | 328 |
How the Prime Check Works
┌─────────────────────────────────────────────────┐
│ is_prime(n) Algorithm │
├─────────────────────────────────────────────────┤
│ 1. If n ≤ 1 → NOT PRIME │
│ 2. If n = 2 → PRIME (only even prime) │
│ 3. If n is even → NOT PRIME │
│ 4. Check divisors from 3 to √n (odd only) │
│ - If any divides n → NOT PRIME │
│ - Otherwise → PRIME │
└─────────────────────────────────────────────────┘
=============== Gemini=====================
Here is the Python program that performs the requested tasks.
def is_prime(n):
"""
Function to check if a number is prime.
Returns True if n is prime, False otherwise.
"""
# Numbers less than or equal to 1 are not prime
if n <= 1:
return False
# Check for factors from 2 up to the square root of n
# We use int(n**0.5) + 1 to include the square root in the range
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
# Main execution block
def main():
primes_list = []
# Find all prime numbers between 1 and 50
# range(1, 51) includes numbers from 1 to 50
for num in range(1, 51):
if is_prime(num):
primes_list.append(num)
# Calculate the sum of these prime numbers
total_sum = sum(primes_list)
# Show the results
print(f"Prime numbers between 1 and 50: {primes_list}")
print(f"Sum of these prime numbers: {total_sum}")
if __name__ == "__main__":
main()
Execution Results
When you run the code above, it will produce the following output:
Prime numbers between 1 and 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of these prime numbers: 328
=============== XiaoMi=====================
def is_prime(n):
"""Check if a number is prime."""
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check odd factors up to the square root
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
# Find all prime numbers between 1 and 50
primes = [num for num in range(1, 51) if is_prime(num)]
# Calculate the sum of these primes
prime_sum = sum(primes)
# Display results
print("Prime numbers between 1 and 50:")
print(primes)
print(f"\nSum of prime numbers: {prime_sum}")
Results:
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of prime numbers: 328
=============== DeepSeek=====================
Here’s a Python program that meets all your requirements:
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check for factors from 3 to the square root of n
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True
def find_primes_in_range(start, end):
"""Find all prime numbers between start and end (inclusive)."""
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes
def calculate_sum(numbers):
"""Calculate the sum of a list of numbers."""
return sum(numbers)
# Main execution
if __name__ == "__main__":
# Define the range
start_num = 1
end_num = 50
# Find prime numbers between 1 and 50
prime_numbers = find_primes_in_range(start_num, end_num)
# Calculate the sum of prime numbers
prime_sum = calculate_sum(prime_numbers)
# Display results
print(f"Prime numbers between {start_num} and {end_num}:")
print(prime_numbers)
print(f"\nNumber of prime numbers found: {len(prime_numbers)}")
print(f"Sum of all prime numbers: {prime_sum}")
# Show the calculation breakdown (optional)
print(f"\nCalculation breakdown: {' + '.join(map(str, prime_numbers))} = {prime_sum}")
Output:
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Number of prime numbers found: 15
Sum of all prime numbers: 328
Calculation breakdown: 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + 31 + 37 + 41 + 43 + 47 = 328
Key Features of the Program:
-
Prime Check Function (
is_prime):- Handles edge cases (numbers ≤ 1, even numbers)
- Only checks odd divisors up to √n for efficiency
- Returns
TrueorFalse
-
Prime Finder Function (
find_primes_in_range):- Iterates through the specified range
- Uses the
is_primefunction to identify primes - Returns a list of prime numbers
-
Sum Calculator (
calculate_sum):- Uses Python’s built-in
sum()function - Could easily be replaced with manual summation if needed
- Uses Python’s built-in
-
Main Execution:
- Defines the range (1-50)
- Calls the functions in logical order
- Displays clear results with formatting
- Includes an optional calculation breakdown
-
Efficiency Considerations:
- The prime check only tests up to the square root of n
- Only odd numbers are tested after 2
- The program uses modular functions for reusability
The program is structured to be clear, efficient, and easily modifiable for different ranges or additional functionality.
================ Qwen====================
Here’s the Python program that meets all the specified requirements:
import math
def is_prime(n):
"""Check if a number is prime."""
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
# Check odd factors up to sqrt(n)
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
# Find all primes between 1 and 50
primes = [num for num in range(1, 51) if is_prime(num)]
# Calculate the sum of prime numbers
prime_sum = sum(primes)
# Display results
print("Prime numbers between 1 and 50:", primes)
print("Sum of these prime numbers:", prime_sum)
Output when executed:
Prime numbers between 1 and 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of these prime numbers: 328
Explanation:
- The
is_prime()function efficiently checks primality by:- Handling edge cases (≤1, even numbers)
- Only checking odd divisors up to √n
- The list comprehension finds all primes between 1-50 (inclusive)
- The sum is calculated using Python’s built-in
sum()function - The output shows both the complete list of primes and their total sum
The program correctly identifies all 15 prime numbers between 1 and 50 (with 2 being the only even prime) and calculates their sum as 328.
================ ChatGLM====================
Here is the Python program that performs the requested tasks.
def is_prime(number):
"""
Checks if a number is prime.
Returns True if prime, False otherwise.
"""
if number <= 1:
return False
# Check for factors from 2 up to the square root of the number
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
def main():
primes = []
# Find all prime numbers between 1 and 50
for num in range(1, 51):
if is_prime(num):
primes.append(num)
# Calculate the sum of these prime numbers
total_sum = sum(primes)
# Show the results
print(f"Prime numbers between 1 and 50: {primes}")
print(f"Sum of these prime numbers: {total_sum}")
if __name__ == "__main__":
main()
Output:
When you execute the code above, the results will be:
Prime numbers between 1 and 50: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of these prime numbers: 328
================ ChatGPT ====================
Below is a complete Python solution that satisfies all four requirements, followed by the actual execution results.
Python Program
# 1. Define a function to check if a number is prime
def is_prime(n: int) -> bool:
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
# 2. Find all prime numbers between 1 and 50
primes_between_1_and_50 = [n for n in range(1, 51) if is_prime(n)]
# 3. Calculate the sum of these prime numbers
sum_of_primes = sum(primes_between_1_and_50)
# 4. Print results
print("Prime numbers between 1 and 50:", primes_between_1_and_50)
print("Sum of prime numbers:", sum_of_primes)
Execution Results
Prime numbers between 1 and 50:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
Sum of prime numbers:
328
If you would like, I can also provide:
- A more beginner-friendly version
- A highly optimized version using a sieve
- Time complexity analysis
- Unit tests for the
is_primefunction
更多推荐


所有评论(0)