Write a program which declares an array of 51 integers Have

Write a program which declares an array of 51 integers. Have the computer find the first 51 prime numbers and store them in the array. Then, using a loop (a \'for\' loop) take the sum of the prime numbers. Then print the median number. Be sure not to write more than 51 prime numbers in the array, that would be writing past the end of the array and that is not good.

Solution


public class Print51Prime {

   public static void main(String[] args)
   {
       int N = 51;
       int[] primes = new int[N];
   int count=0;
   int num=2;
  
   while(count!=N)
   {
   boolean prime=true;// to determine whether the number is prime or not
   for (int i=2;i<=Math.sqrt(num);i++)//efficiency matters
   {
   if (num%i==0)
   {
   prime=false;// if number divides any other number its not a prime so set prime to false and break the loop.
   break;
   }

   }
   if (prime)
   {
   primes[count++] = num;
   }
   num++;
   }
  
   int sum = 0;
   System.out.println(\"List of first \" + N + \" prime numbers: \");
   for (int i = 0; i < N; i++)
   {
       System.out.print(primes[i] + \" \");
       sum += primes[i];
   }
   System.out.println();
   int median = primes[N/2];
   System.out.println(\"Sum of first \" + N + \" prime number is \" + sum);
   System.out.println(\"Median of first \" + N + \" prime number is \" + median);
  
   }
  
}

 Write a program which declares an array of 51 integers. Have the computer find the first 51 prime numbers and store them in the array. Then, using a loop (a \'

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site