Write a complete java program, called MyProgram, that has the following properti
ID: 3684276 • Letter: W
Question
Write a complete java program, called MyProgram, that has the following properties:
-A method, called computeSum, that receives 2 integer values, say A and B, and returns the sum of all values between A and B (including A and B). A must be less than B for the method to return the sum. Otherwise the method returns 0. No printing inside the method.
-A method, called isPrime, that receives the sum and determines if the sum is a prime number by returning true if the number is prime and false if the number is not prime. No printing inside the method.
Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Scanner;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int computeSum(int a,int b){
int sum = 0;
for(int i=a;i<=b;i++)
sum += i;
return sum;
}
public static int isPrime(int sum){
for(int i=2;i<=sum/2;i++)
if(sum % i == 0)
return 0;
return 1;
}
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Enter two numbers");
Scanner in = new Scanner(System.in);
int a,b;
a = in.nextInt();
b = in.nextInt();
int sum = computeSum(a,b);
System.out.println("The sum = "+sum);
if(isPrime(sum)==1)
System.out.println("The sum is a prime number");
else
System.out.println("The sum is not a prime number");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.