Write a Java program to compute the sum of the first 100 prime numbers


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.*;
  2. public class Javaexcercise {
  3. public static void main(String[] args)
  4. {
  5. int sum = 1;
  6. int ctr = 0;
  7. int num = 0;
  8.  
  9. while (ctr < 100) {
  10. num++;
  11. if (num % 2 != 0) {
  12. // check if the number is even
  13. if (is_Prime(num)) {
  14. sum += num;
  15. ctr++;
  16. }
  17. }
  18. }
  19. System.out.println("\nSum of the first 100 prime numbers is: "+sum);
  20. }
  21.  
  22. public static boolean is_Prime(int num) {
  23. for (int i = 3; i * i <= num; i+= 2) {
  24. if (num % i == 0) {
  25. return false;
  26. }
  27. }
  28. return true;
  29. }
  30. }

Result

java techstudy.org

     





Related Topics




Popular Posts