![]() |
VOOZH | about |
Given a positive integer n, compute and return the sum of all prime numbers between 1 and n (inclusive).
Examples:
Input : 10
Output : 17
Explanation : Primes between 1 to 10 : 2, 3, 5, 7.Input : 11
Output : 28
Explanation : Primes between 1 to 11 : 2, 3, 5, 7, 11.
This method checks each number from 2 to
nfor primality by dividing it by all numbers from 2 toi/2. If any divisor is found, the flag is set to 0, indicating the number is not prime. If no divisors are found, the number is added to the sum. After completing the loop, the sum of all primes up tonis returned.
17
To optimize the above method, we check whether a number is prime by iterating only up to the square root of the number. This approach checks each number from 2 to
nfor primality by testing divisibility up to its square root. If a number is prime (i.e., it has no divisors other than 1 and itself), it is added to the sum. Finally, the sum of all prime numbers up tonis returned.
17
The idea is to use Sieve of Eratosthenes to efficiently check which numbers are prime in the range from 1 to n.
This process marks all prime numbers up to
nby iterating through the numbers and marking their multiples as non-prime. After completing the marking, it sums up all the numbers that remain marked as prime.
17