In: Computer Science
Using Java:
Create a class called MyNumber with an integer private attribute.
Create a constructor that defines an integer parameter to set the private integer attribute.
Create a setter that validates the attribute does not accept a value lower than 2 or the method will throw a IllegalArgumetException.
Create a getter to return the private integer attribute value.
Define a public method that is called isPrime() that returns a boolean and implements the Sieve of Eratosthenes method.
Define a public method that is called numberOfPrimes() that returns the number of prime numbers between 2 and the private attribute value.
Demonstrate this object in a main method that allows the user to interact with all the public methods of your class.
Refer to code snippet below. Output is attached.
public class MyClass {
private int n;
public MyClass() {}
public MyClass(int n) throws Exception //param constructor
{
if(n<2)
{
throw new IllegalArgumentException("Number is less than 2");
}
else
{
this.n = n;
}
}
public void setNum(int n) throws Exception //setter method
{
if(n<2)
{
throw new IllegalArgumentException("Number is less than 2");
}
else
{
this.n = n;
}
}
public int getNum()//getter method
{
return this.n;
}
public boolean isPrime() //O(root(n))
{
for(int i = 2; i<Math.sqrt(this.n); i++)
{
if(this.n%i == 0)
{
return false;
}
}
return true;
}
public int numberOfPrimes() //implements SOE
{
boolean prime[] = new boolean[n+1];
int count = 0;
for(int i=0;i<this.n;i++)
prime[i] = true;
for(int p = 2; p*p <=this.n; p++)
{
if(prime[p] == true)
{
for(int i = p*p; i <= this.n; i += p)
prime[i] = false;
}
}
for(int i = 2; i <= this.n; i++)
{
if(prime[i] == true)
count++;
}
return count;
}
public static void main(String[] args) throws Exception{
MyClass cl = new MyClass(20);
System.out.println(cl.isPrime());
System.out.println(cl.numberOfPrimes());
System.out.println(cl.getNum());
}
}
Output:
false
8
20