Sum of Prime Numbers Up to N

Calculate the sum of all prime numbers less than or equal to a given positive integer n. A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.

Method Signature

public static Integer sumOfPrimes(Integer n)

Examples

Example 1:

Input: n = 10
Output: 17
Explanation: The prime numbers less than or equal to 10 are 2, 3, 5, 7. Their sum is 2 + 3 + 5 + 7 = 17.

Example 2:

Input: n = 5
Output: 10
Explanation: The prime numbers less than or equal to 5 are 2, 3, 5. Their sum is 2 + 3 + 5 = 10.

Example 3:

Input: n = 2
Output: 2
Explanation: The only prime number less than or equal to 2 is 2 itself.

Example 4:

Input: n = 1
Output: 0
Explanation: There are no prime numbers less than or equal to 1.

Example 5:

Input: n = null
Output: null
Explanation: Return null for null input.
Apex Code Editor

Welcome to Lightning Challenge!

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay November 2026 (Nov 16–30)Sponsored by FLXBL

Contest runs November 16 - 30. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 15 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In