Computer Science, asked by S1127, 11 months ago

write a Java program to print the given pattern

Attachments:

Answers

Answered by QGP
0

Prime Number Pattern in Java

Prime Numbers are those which have exactly two factors: 1 and the number itself.

A few examples include 2, 3, 5, 7, 13, 29, 101, etc.


Here we are given the task of a printing a pattern using prime numbers.


There are 4 rows. So we must run a loop which iterates 4 times. We then need an inner loop whose exit condition would depend on the outer loop variable.

Inside the inner loop, we must print primes. So we would need another variable for it, which needs to increment until it becomes a prime.


Here is a Java program to print the pattern:


public class Brainly

{

   public static void main(String[] args)

   {

       int p = 2;          //This variable will contain the prime numbers

       

       for(int i=0;i<4;i++)        //Outer Loop prints 4 rows

       {

           for(int j=0;j<=i;j++)   //Inner Loop runs to print elements in each row

           {

               while(!isPrime(p))  //Until p becomes a prime, it is incremented

               {

                   p++;

               }

               System.out.print(p+" ");    //The prime p is printed

               p++;        //Incrementing p so that new primes can be obtained in next iteration

           }

           System.out.println();   //Printing new line after completion of each row

       }

   }

   

   static boolean isPrime(int n)       //Function to check whether an integer is prime or not

   {

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

       {

           if(n%i==0)      //We check divisibility of n by each number from 2 to sqrt(n)

               return false;       //If n is divisible then it is not prime and false is returned

       }

       

       return true;        //If no divisibility is found, then true is returned

   }

}



Attachments:
Similar questions