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!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

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

🏆 All Time Leaderboard

Contest runs January 1, 1970 - December 31, 9999. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.