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

Note

You can test your code by connecting to Salesforce, but to save your progress and earn points, you'll need to create an account. Your solutions and achievements will be tracked automatically once you're logged in.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In