Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class hw4 {
- public static void main(String[] args) {
- for(;;)
- {
- Scanner kb = new Scanner(System.in);
- int N,option;
- System.out.println("Enter N");
- N = kb.nextInt();
- System.out.println("Choose option");
- System.out.println("1- Sum of numbers from 1 to N\n2- Perfect squares from 1 to N\n3- Prime numbers from 2 to N\n4- sum, average, min, and max.\n5- Exit");
- option = kb.nextInt();
- int sum=0,max=0,min=0,avg=0;
- if (N >= 1){
- max = N;
- min = 1; }
- else {
- max = 1;
- min = N;
- }
- for (int i = 1;i <= N; i++)
- {
- sum += i;
- avg = avg + 1;
- }
- switch(option)
- {
- case(1):
- System.out.println("The Sum is : " + sum);break;
- case(2):
- System.out.println("The Perfect numbers are :");
- double x;
- for (int i = 1;i <= N; i++)
- {
- x = Math.sqrt(i);
- if (x - (int)x == 0)
- System.out.println(i );
- }
- break;
- case(3):
- System.out.println("The Prime numbers are :");
- for (int i = 1;i <= N; i++)
- {
- if (isPrime(i) == true)
- System.out.println(i);
- }
- break;
- case(4):
- System.out.println("The Sum is : " + sum);
- System.out.println("The Avg is : " + ((float)sum/avg));
- System.out.println("The Max is : " + max);
- System.out.println("The Min is : " + min);
- break;
- case(5):
- System.exit(1);
- break;
- default: System.out.println("Choose a right option");
- }
- System.out.println("=======================================================");
- }
- }
- public static boolean isPrime(int n) {
- if (n <= 1) {
- return false;
- }
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (n % i == 0) {
- return false;
- }
- }
- return true;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement