Computer Science, asked by siddhimulia8, 1 month ago

write a menu driven program to accept a number and check and display whether it is a prime number or a perfect number.

Answers

Answered by himanshu2006vps
6

Answer:

import java.util.Scanner;

class PrimeperfectCheck

{

public static void main(String args[])

{

Scanner in= new Scanner(System.in);

System.out.println("1.For prime number");

System.out.println("2.For perfect number");

System.out.println("Enter your choice");

int ch= in.nextInt()

switch(ch)

{

case 1:

{

int temp;

boolean isPrime=true;

System.out.println("Enter any number:");

int num=in.nextInt();

in.close();

for(int i=2;i<=num/2;i++)

{

temp=num%i;

if(temp==0)

{

isPrime=false;

break;

}

}

if(isPrime)

System.out.println(num + " is a Prime Number");

else

System.out.println(num + " is not a Prime Number");

break;

}

case 2:

{

long n,sum=0;

System.out.println("Enter a number");

n=in.nextLong();

int i=1;

while(i<=n/2)

{

if(n%i==0)

{

sum+=i;

}

i++;

}

if(sum==n)

{

System.out.println(n+" is a perfect number");

}

else

System.out.println(n+" is not a perfect number");

}

default:

System.out.println("Wrong choice");

}

}

}

Answered by TheUntrustworthy
46

(Note: A perfect number is a number which is equal to the sum of its factors excluding the number itself. E.g: 6 is a perfect no as the sum of its factors 1 + 2 + 3 = 6)

Program : (Using Scanner class)

import java.util.*;

public class MenuPrimePerfect {

public static void main(String args[])

{ int ch,n,num;

Scanner inp=new Scanner(System.in);

System.out.println("M E N U ");

System.out.println("1. To check Prime no.");

System.out.println("2. To check Perfect no.");

System.out.println("3. To exit.");

System.out.println("Enter your choice :");

ch=inp.nextInt();

System.out.println("Enter one no :");

n=inp.nextInt();

switch(ch)

{ case 1: int i,c=0;

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

{ if(n%i==0)

c++;

}

if(c==2)

System.out.println("It's a PRIME NUMBER");

else

System.out.println("It's NOT A PRIME NUMBER");

break;

case 2 : num = n;

int s=1;

for(i=2;i<=n/2;i++)

{ if(n%i==0)

s=s+i;

}

if(s==num)

System.out.println("It's a PERFECT NUMBER");

else

System.out.println("It's NOT A PERFECT NUMBER");

break;

case 3 : System.out.println("Thanks. See you again!");

break;

default : System.out.println("Input error!!!");

} } }

Similar questions