Java program to find sum of prime numbers which are less than a given number

Java program to find sum of prime numbers which are less than a given number thumbnail
23K
By Dhiraj Ray 01 January, 2018

Description

Write a java program to find the sum of all the prime numbers less then a given natural number N. The main purpose of this inteview question is to check the programming sense and capabilities to check how good you are to convert existing logic into code. The question is mostly asked to freshers.The only main logic in this program is to find the prime numbers.Prime number is a number that is greater than 1 and divided by 1 or itself.For reminder, 2 is also a prime number.

PrimeNumberSum.java
package com.devglan;

public class PrimeNumberSum {

    public long sum(int limit){
        int number = 2;
        int count = 0;
        long sum = 0;
        while(count < limit){
            if(isPrimeNumber(number)){
                sum += number;
                count++;
            }
            number++;
        }
        return sum;
    }

    private boolean isPrimeNumber(int number){

        for(int i=2; i<=number/2; i++){
            if(number % i == 0){
                return false;
            }
        }
        return true;
    }

    public static void main(String args[]){
        PrimeNumberSum primeNumberSum = new PrimeNumberSum();
        System.out.println(primeNumberSum.sum(1000));
    }

}

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.