w3resource

Java Exercises: Compute the sum of first n given prime numbers

Java Basic: Exercise-232 with Solution

Write a Java program to compute the sum of first n given prime numbers.

Input:

n ( n ≤ 10000). Input 0 to exit the program.

Pictorial Presentation:

Java Basic Exercises: Compute the sum of first n given prime numbers.

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 
        public static void main(String[] args) throws java.io.IOException{
            Scanner scan = new Scanner(System.in);
                int count=0;
                int sum=0;
	System.out.println("Input a number (n<=10000) to compute the sum:");
	int n=scan.nextInt();
                for(int i=2;;i++){
                    if(prime(i)){
                        count++;
                        sum+=i;
	 if(count==n)break;
	    }
	         } 
	System.out.println("Sum of first "+n+" prime numbers:"); 
                System.out.println(sum);
	}				
         public static boolean prime (int n){
                if(n==1)return false;
                for(int i=2;i<=Math.sqrt(n);i++)
                    if(n%i==0)return false;
                return true;
            }
}

Sample Output:

Input a number (n<=10000) to compute the sum:
100
Sum of first 100 prime numbers:
24133

Flowchart:

Flowchart: Compute the sum of first n given prime numbers.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.
Next: Write a Java program that accept a even number (n should be greater than or equal to 4 and less than or equal to 50,000, Goldbach number) from the user and create a combinations that express the given number as a sum of two prime numbers. Print the number of combinations.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK