Computer Science, asked by MeghaLakshmiB, 9 months ago

Question 8
Write a program to calculate the sum of all the prime numbers between the range of
1 and 100.

Answers

Answered by QGP
3

Sum of Primes - Java

We wish to find the sum of primes from 1 to 100. It is clear that we need to create a function that checks whether a given number is prime or not.

We initialize a Sum variable to 0, and loop through all numbers from 1 to 100. If a number is prime, we add that to Sum. The Sum is displayed at the end.

To check if a number n is prime, we need to check if it is divisible by any integer from 2 to \sqrt{n}. If it is, then the number n is not prime. If we do not find any divisibility, then the number n is indeed prime.

So, here we create a boolean isPrime(int n) function, which loops through the numbers from 2 to \sqrt{n}. If n is divisible by any number in this loop, we return false. If the loop finishes and no divisibility is found, we return true.

Note that a function will stop executing once a return statement is reached.

This way, we can check whether a number is prime and add it to Sum.

 \rule{300}{1}

SumOfPrimes.java

public class SumOfPrimes {

   //Function to check if a number is prime

   static boolean isPrime(int n) {

       //Check divisibility by all numbers from 2 to sqrt(n)

       for(int i=2; i<=(int)Math.sqrt(n); i++) {

           if(n%i == 0) {

               return false;

           }

       }

       //If no divisibility is found, number is prime. Return true

       return true;

   }

   

   public static void main(String[] args)

   {

       int lowerLimit = 1;         //Set Lower Limit

       int upperLimit = 100;       //Set Upper Limit

       int Sum = 0;                //Initialize Sum variable

       //Smallest prime is 2. So, start loop from max(2, lowerLimit)

       for(int i = Math.max(2, lowerLimit); i <= upperLimit; i++) {

           if(isPrime(i)) {

               Sum += i;

           }

       }

       //Print Sum

       System.out.println("Sum of primes from "+lowerLimit+" to "+upperLimit+" is: "+Sum);

   }

}

Attachments:
Similar questions