Computer Science, asked by kvnmurty, 10 months ago

write a program to find if the given integer is a prime number or not.

Answers

Answered by BrainlyPromoter
35
Sample program to calculate whether the entered integer is a prime number or not

import java.util.Scanner;
public class PrimeNumberChecker

{

public static void main(String args[])

{

Scanner prince = new Scanner ( System.in );
double n = prince.nextDouble( );
int p = 0;
for ( int c = 1 ; c < = n ; c ++ )

{

if( n % c == 0 )

{

k = k + 1;


}
}
if( k == 2 )
{

System.out.println("Entered number is prime. ");
}
else
{
System.out.println(" Entered number is not prime.");
}
}
}

no4: Very nice
BrainlyPromoter: thanks
Answered by Anonymous
39

CODE :

import java.util.*;

class random

{

   public static void main(String args[])

   {

       Scanner sc=new Scanner(System.in);

       System.out.println("Enter a number to check whether the given number is prime number or not ");

       int n = sc.nextInt();

       int c = 0;

       for(int i=1;i<=n;i++)

       {

           if(n%i==0)

           {

               c++;

           }

       }

       if(c==2)

       {

           System.out.println("The entered number is a prime number");

       }

       else

       {

           System.out.println("The entered number is not a prime number");

       }

   }

}

Explanation:

Actually welcome to the concept of OOP ( Object Oriented Programming ) .

The main feature of OOP is that it not only gives equal importance to data and procedure but also protects data while using several principles called encapsulation , data hiding , abstraction .

JAVA uses the concept of OOP .

In JAVA , a class is a group of objects having some common characteristics and hence the class is known as object factory .

Object is nothing but an entity with unique properties .

We take user input with a package called java.util .

We use a special class called Scanner Class which helps in taking user inputs .

" A Prime Number Logic "

A prime number is a number which has exactly two factors - the number and itself . Hence we can take a number as input and then check the number of factors of the number in order to check whether a number is prime or not .

" Taking input "

Taking input needs the use of Scanner class as discussed earlier . We need to print a statement so that the users understands that he/she has to input something . The printing is done by "System.out.println" .

" Loop "

A loop is a repetition of many statements .

Here "for-loop" is used to execute the statements . The value of 'i' begins from 1 and goes till n .

This is similar to summation .

" If else statement "

Now the last portion of the code involves the use of if else statement .

Here we will check whether the number has two factors or more than two factors .

Hence we can easily find whether the number is prime or not .

OUTPUT in attachment .

Attachments:

tanmoyvestige: sabash jishnu
no4: Very nice
Similar questions