prime numbers test in java - java

I have an assignment that tells me to do the following:
Create a method named IsPrime(), which accepts a positive integer as a parameter. If a number if prime, the method should return true. (A prime number is evenly divisible only by 1 and itself). Incorporate this method into a class named MyMathMethods. Create a main() method in a separate class called MainFile, which will test IsPrime() by asking the user for a number using an input dialog and will then report whether that number is prime or not.
How do I connect these two files?
here is my code:
package x;
import java.util.Scanner;
public class MyMathMethod
{
public static boolean isPrime(int num)
{
int result=0;
System.out.println("enter no");
Scanner s = new Scanner(System.in);
num =s.nextInt();
long sqrt = (int) Math.sqrt(num);
for(long divisor = 2; divisor <= sqrt; divisor++)
{
if(num % divisor == 0)
{
// This only needs to happen once
// for this number to NOT be prime
return false;
}
}
// If we get here, the number is prime.
return true;
}
}
Another File is
import x.*;
package y;
public class MainFile {
public static void main(String [] args) {
boolean isNumberPrime;
int num;
MyMathMethod methods = new MyMathMethod();
isNumberPrime = methods.isPrime(num);
{
if(num=true)
System.out.println(num + " is Prime Number");
else
System.out.println(num + " is not Prime Number");
}
}
}
Thanks in advance.

Do you want to call the method isPrime() from your main in another class?
When they're a in the same package, you have to create a new instance of your class MyMathMethods and call the method isPrime(). when they're in different class, you must import the missing class and do the same as above. If you don't import it manually, probably your IDE will do it for you or ask for it.
the first file:
package x;
public class MyMathMethods {
public boolean isPrime(int number) {
//your code here
return false;
}
}
the second:
package y;
import x.* //importing all files from the package x
//if your class MyMathMethods is in the same package, you don't need that
public class MainFile {
public static void main(String [] args) {
int number = 20;
boolean isNumberPrime;
MyMathMethods methods = new MyMathMethods();
isNumberPrime = methods.isPrime(number); //here the result if it's prime
}
}
EDIT: I'll try to fix your code.
If you want to have your method static, you can call it:
MyMathMethods.isPrime(numer);
without the need to create a new instace.
The next issue: why are you passing to the funtion a variable that is not initialized (num) and try to get this value from the input in this method? Well, that's not a good practise. I would rather suggest to get the input from the user in main (directly in main on in another function called up in main) and then pass the value to isPrime().
package y;
import x.*
public class MainFile {
public static void main(String [] args) {
int num;
Scanner s = new Scanner(System.in);
num =s.nextInt();
if(MyMathMethods.isPrime(num)) {
//if true, your code;
} else {
//false, your code;
}
}
}
package x;
public class MyMathMethod {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Your algoritm failed for many numbers, e.g. 0, 1, 2. Well, for this values it doesn't even returned any value. Please always protect your method against any possible wrong parameters.

Related

Error in test cases for a recursion problem

I am solving a code for competitive programming and my code which I think is correct is throwing an error for some test cases:
The question is to find the total number of digits in an integer using recursion.
My Code:
import java.util.*;
import java.io.*;
import java.lang.*;
class Driver_class
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n =sc.nextInt(); // taking number "n" as input
System.out.println(new Digitcount().countDigits(n)); // prints the count of digits
}
}
}
class Digitcount
{
static int count=0;
public static int countDigits(int n)
{
if(n<1)
return 0;
countDigits(n/10);
count++;
return count;
}
}
The count variable is the total number of digits.
The test case that this code fails:
However, this code passes all the test cases:
class Digitcount
{
static int count=0;
public static int countDigits(int n)
{
if(n<1)
return 0;
return countDigits(n/10)+1;
}
}
I dont see a difference in any of my codes regarding the output value. What is causing the first code to fail the test case?
The difference is in use of a static variable. It will hold the result between tests and thus in any test after the first one it will be incorrect. If you have two calls one after the other like so:
int a = countDigits(605);
int b = countDigits(605);
The result will be a==3, b==6 - the first result is carried over to the second call.

StackOverFlowError in java program [duplicate]

This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 7 years ago.
I am trying to solve a problem which asks to find the smallest prime palindrome, which comes after a given number which means that if the input is 24, the output would be 101 as it is the smallest number after 24 which is both prime and a palindrome.
Now my code works perfectly for small values but the moment I plug in something like 543212 as input, I end up with a StackOverFlowError on line 20, followed by multiple instances of StackOverFlowErrors on line 24. Here is my code :
package nisarg;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrome(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void isPalindrome(long num) {
String word = Long.toString(num);
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
isPalindrome(num + 1);
}
}
if (i == word.length() / 2) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
isPalindrome(num + 1);
}
}
}
}
All shown exiting solutions use recursion and have the problem that at some point they will reach the point where a StackOverflowException will occur.
A better solution which would also be parallelizable would be to change it into a loop.
It could be something like:
package nisarg;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
public class Chef_prime_palindromes {
private static final CopyOnWriteArrayList<BigInteger> PRIMESCACHE
= new CopyOnWriteArrayList<>();
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
BigInteger num = new BigInteger(input.nextLine());
initPrimes(num);
for (num = num.add(BigInteger.ONE);
!isPrimePalindrome(num);
num = num.add(BigInteger.ONE));
System.out.println(num.toString());
}
}
private static void initPrimes(BigInteger upTo) {
BigInteger i;
for (i = new BigInteger("2"); i.compareTo(upTo) <= 0 ; i = i.add(BigInteger.ONE)) {
isPrime(i);
}
}
public static boolean isPrimePalindrome(BigInteger num) {
return isPrime(num) && isPalindrome(num);
}
// could be optimized
public static boolean isPrime(BigInteger num) {
for (int idx = PRIMESCACHE.size() - 1; idx >= 0; --idx) {
if (num.mod(PRIMESCACHE.get(idx)).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
if (!PRIMESCACHE.contains(num)) {
PRIMESCACHE.add(num);
}
return true;
}
public static boolean isPalindrome(BigInteger num) {
String word = num.toString();
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
return false;
}
}
return true;
}
}
A new String object is created in each recursive call and placed onto stack (the place where all variables created in methods are stored until you leave the method), which for a deep enough recursion makes JVM reach the end of allocated stack space.
I changed the locality of the String object by placing it into a separate method, thus reducing its locality and bounding its creation and destruction (freeing of stack space) to one recursive call.
package com.company;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrom(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static void isPalindrom(long num) {
for (; ; ) {
if (isPalindrome(num)) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
num++;
}
} else {
num++;
}
}
}
public static boolean isPalindrome(long num) {
String string = String.valueOf(num);
return string.equals(new StringBuilder(string).reverse().toString());
}
}
First thing you should be aware of is the fact that your resources are limited. Even if your implementation was precise and all recursive calls were correct, you may still get the error. The error indicates your JVM stack ran out of space. Try to increase the size of your JVM stack ( see here for details).
Another important thing is to look for the distribution of prime and palindrome numbers. Your code runs by testing every num+1 against palindrome property. This is incorrect. You test for palindrome only when the number is prime. This will make the computation much much easier (and reduce recursive calls). I have edited your code accordingly and got the closest palindrome number after 543212 (1003001) . Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
//isPalindrome(num+1);
nextPrimePalindrome(num+1);
}
public static void nextPrimePalindrome(long num)
{
boolean flag=true;
while(flag)
{
if(isPrime(num))
if(isPalindrome(num))
{
System.out.println(num);
flag=false;
}
num++;
}
}
public static boolean isPrime(long num){
long i;
for(i=2;i<num;i++){
if(num%i == 0){
return false;
}
}
return true;
}
public static boolean isPalindrome(long num)
{
String word=Long.toString(num);
for(int i=0;i<word.length()/2;i++)
if(word.charAt(i)!=word.charAt(word.length()-i-1))
return false;
return true;
}
}

How do I implement "this" into my Java program?

It's a requirement of my school assignment that I use "this" in the following program. However, I can't quite figure out where I could put this. I keep getting a "non-static variable this cannot be referenced from a static context" error.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
System.out.println("Enter the upper limit for the prime numbers computation: ");
int upperLimit = new Scanner(System.in).nextInt();
int count = 0;
for(int number = 2; number<=upperLimit; number++)
{
if(isPrime(number))
{
System.out.println(number);
count++;
}
}
System.out.println("Number of primes generated: " + count);
}
public static boolean isPrime(int number)
{
for(int i=2; i<number; i++)
{
if(number%i == 0)
{
return false;
}
}
return true;
}
}
The Java keyword this refers to the instance of your class that invoked an instance method. A static method is general to its class, and so you cannot reference any instance (non-static) variables from within it. You can only access instance variables like this from within an instance method, that is, a method that is not defined as static.
So, you would need to create an instance method (of which there are none in your class), in order to use this.
This is nothing more than a reference to the object on which the method was called. Static methods on the other hand can operate without any instance of the class even exisiting, therefore they can't have reference to any object. That's why you can't use this in static method. If you really need this, you have to remove static keywords from your functions and use instance variables in those functions anyhow.
public class PrimeNumber
{
public int count = 0;
public int upperLimit;
public static void main(String args[])
{
PrimeNumber pn = new PrimeNumber();
System.out.println("Enter the upper limit for the prime numbers computation: ");
pn.upperLimit = new Scanner(System.in).nextInt();
pn.doCheck();
System.out.println("Number of primes generated: " + pn.count);
}
public void doCheck() {
for (int number = 2; number <= this.upperLimit; number++)
{
if (this.isPrime(number))
{
System.out.println(number);
count++;
}
}
}
public boolean isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
}

Inheritance and InputBox

So I have a super class called Factorial and two subclasses called Fibonacci and Arithmetic. In my main super class which I call the method using a polymorphic array from my main class, I have an input box inquiry that I want to only show up once, but instead it shows up multiple times. Is there anyway I can stop this? My main class is called PolyMorphism. I know it's tedious but it's the way I made the program and want it to be :p
public class Polymorphism {
public static void main(String[] args) {
Factorial arrayObject[] = new Factorial[3];
arrayObject[0] = new Factorial();
arrayObject[1] = new Fibonacci();
arrayObject[2] = new Arithmetic();
for(int x=0;x<arrayObject.length;++x){
arrayObject[x].sequence();
}
public class Factorial extends JFrame {
//this input box shows up 3 times when I launch.
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
public void sequence(){
System.out.println("Factorial:");
System.out.println(fact(Integer.valueOf(valueInput)));
public static long fact (int n){
if (n <= 1){
return 1;
}else
return n * fact(n-1);
}
public class Fibonacci extends Factorial {
public void sequence(){
int inputValue = Integer.parseInt(valueInput);
System.out.println("Fibonacci Sequence");
/**for (int value = 0; value < inputValue; value++){
System.out.println(fibonacciSequence(value));
} **/
System.out.println(fibonacciSequence(inputValue));
}
public static long fibonacciSequence(int v) {
// TODO Auto-generated method stub
if(v == 0) {
return 0;
}else if (v <= 2){
return 1;
}
long fibonacci = fibonacciSequence(v - 1) + fibonacciSequence(v-2);
return fibonacci;
}
}
The comment with the problem is under the Factorial class, and disregard the JFrame for now.
In your Factorial class, you have this:
public final String valueInput = JOptionPane.showInputDialog("Please enter a number between 1 and 20.");
Which means every time you create an instance of it or a subclass, that input dialog will pop up.
The answer is: Don't do that.
Put it in a method and call the method when you want the input dialog to show.
Each Factorial instance (of which you have three) has its own valueInput property, so the behavior is as expected. You could make this field static (and therefore shared), but it's still not clear what you're trying to accomplish.
It's most likely the case that you should be separating the input display from the Factorial implementation entirely.

Can't get method (getTest) to return true boolean method result if input matches a number in my array list

I can't seem to get the "The numbers match" result if my input is a number that is in my array list in another class called SomeNumbers. If you run it, it will give you the result for it not being a number in the array at the speed of light though.
I am also having a hard time pin pointing where the actual problem is because I can use my debugging tools for whatever reason in jGrasp.
This is the main application that the user would input the number to see if there is a match.
import java.util.Scanner;
public class SomeNumbersClient {
public static void main(String[] args) {
SomeNumbers testNumbers = new SomeNumbers();
Scanner userInput = new Scanner(System.in);
System.out.print("Enter Integer Value: ");
int input = userInput.nextInt();
testNumbers.setNumber(input);
if (testNumbers.getTest()) {
System.out.println("The numbers match");
} else {
System.out.println("The numbers don't match");
}
}
}
Now this is the class where I call on the getTest method to see if the boolean result is true or false. I then have the if statement in the client see if it's true then it will display that there is a match, if not, there is no match.
public class SomeNumbers {
private int[] numbers = { 5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 8080152, 4562555, 5552012, 5050552, 7825877, 120255, 1005231, 6545231, 3852082, 7576651,7881200, 4581002};
private int number;
private int index = 0;
private boolean test = true;
public void setNumber(int input) {
number = input;
}
public boolean getTest(){
while (index < numbers.length){
if (number != numbers[index]){
test = false;
index++;
} else {
test = true;
}
}
return test;
}
}
Sorry the code kind of got chopped up, any help is appreciated.
here is proper version of getTest function, your problem was because you find match (and set variable test to true), but then you continue search and next number converts "test" to false
public boolean getTest()
{
index = 0;
while (index < numbers.length)
if (number != numbers[index])
index++;
else
return true;
return false;
}

Categories