Error with repetition which I can't spot - java

I'm trying to sort out some homework regarding "repetition" with the while statement. The homework is asking me to input a number and tell if said number is prime. So far, I've come with this:
class Prime {
boolean esPrime(int n) {
boolean prime = true;
int divisor = 2;
while (prime && divisor != n) {
if (n % divisor == 0) {
prime = false;
} else {
divisor++;
}
}
return prime;
}
}
Then I stated this "boolean test" in the main method to check if that piece of code worked:
boolean testEsPrime = esPrime(2) == false;
public static void main(String[] args) {
Prime p = new Prime();
System.out.println("testEsPrime = " + p.testEsPrime);
}
And whenever I run it I get false and I can't seem to be able to spot the error. Any clue why this happens?

It's not the most efficient code in the world, but it works for me (see below). I'm not sure what the problem is here! Incidentally, you only need to test 2 and odd factors up to the square root of the thing you're testing, and a more efficient approach in general (for determining what numbers are primes in bulk) is to use a Sieve of Erastothenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes).
The reason you get false for the test you do is that esPrime(2) == false is false - that is, esPrime(2) == true.
class Prime {
boolean esPrime(int n) {
boolean prime = true;
int divisor = 2;
while (prime && divisor != n) {
if (n % divisor == 0) {
prime = false;
}
else {
divisor++;
}
}
return prime;
}
public static void main(String[] args) {
Prime p = new Prime();
for(int i=2; i<10; ++i) {
System.out.println("esPrime(" + i + ") = " + p.esPrime(i));
}
}
}
Output:
esPrime(2) = true
esPrime(3) = true
esPrime(4) = false
esPrime(5) = true
esPrime(6) = false
esPrime(7) = true
esPrime(8) = false
esPrime(9) = false

Related

Method with boolean return type not working inside main()

I had static method which is to find out prime number and it is working fine but the same method i am trying to keep inside main method it is throwing errors by stating illegal modifiers for parameter and void method does not return value
the same code is working fine outside of main method, any one plz sugggest me why it is not working in main() . Thanks ..!!
My method
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
Inside main() with lot of error message
inside main
Solution
Thanks Logan --- need to add methods outside main method
my working code is added below
public class Squar {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
Squar s = new Squar();
//System.out.println(s.isPrime(num));
scan.close();
System.out.println("M2 "+s.isPrimeNumber(num));
}
public boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You are getting this error because Java does not support nested function.
You are implementing method inside other method, that is not possible. to nest methods use lambdas in java 8.
have a look at Can methods in java be nested and what is the effect? [closed]

Break Iteration of Java loop with control flow with a recursive method

My attempt at recursion by trying to solve the monkey/coconut/sailor problem.
Im having issues with my for loop stopping. It just iterates though and im unsure where I went wrong.
in my 3 test cases the method testCoconuts returns the values I would like, however my loop will iterate until the last number, even if the true values are sent through the loop.
im sure its my booleans, but i havent been able to figure out what im doing wrong.
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
if (c % s == 1 && sr > 0) {
Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1) {
return false;
}
else if (sr == 0) {
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return false;
}
public static void main(String[] args) {
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
Test.testCoconuts(2, 2, 7); //will print solved
Test.testCoconuts(3, 3, 79); //will print solved
Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++) {
if (Test.testCoconuts(sailors, sailors, testNuts)==true) {
System.out.println("solved!");
break;
}
else {
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}
The for-loop will run until the testCoconouts method equals true.
Now if you take a look at the method, there are four possible outcomes:
if (c % s == 1 && sr > 0)
else if (c % s != 1)
else if (sr == 0)
none of the above was satisfied
However, only in the last three of them have you explicitly stated what value the method should return.
So - in the first outcome, since nothing else is said, the method will always return false as stated outside of the if-statements. I assume you want to return the result from the recursion itself, right?
Try changing the first if-statement like this and see what happens :)
if (c % s == 1 && sr > 0) {
boolean result = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
return result;
}
(Could be done in a one-liner without the variable result, but I splitted it up for clarity)
Please remember that you call your function recursively and sending a return back to the previous function call, not to the main
Here is a solution:
public class Test {
public static boolean testCoconuts(int s, int sr, int c){
boolean flag = false;
if (c % s == 1 && sr > 0){
flag = Test.testCoconuts(s, sr - 1, c - (c/s) - 1);
}
else if (c % s != 1){
return flag;
}
else if (sr == 0){
System.out.println("solved");
return true; //returns true in all 3 test cases below
}
return flag;
}
public static void main(String[] args){
//int s and sr must me entered into the test program
//as the same number, ex s= 2, sr = 2
int sailors = 3;
//Test.testCoconuts(2, 2, 7); //will print solved
//Test.testCoconuts(3, 3, 79); //will print solved
//Test.testCoconuts(4,4,1021); //will print solved
for (int testNuts = 1; testNuts < 100; testNuts++){
boolean flag = Test.testCoconuts(sailors, sailors, testNuts);
System.out.println(testNuts);
if (flag==true){
System.out.println("solved!");
break;
}
else{
System.out.println(testNuts);
System.out.println("next iteration");
System.out.println(testNuts);
}
}
}
}

Design a class that tells whether a number is prime or not

My homework is to Design a class named MyInteger with the following conditions:
An int data field named value that stores the int value of an integer.
A constructor that creates a MyInteger object for the specified int value.
A get method that returns the int value.
A method, isPrime() that returns true if the value is a prime number. See -section 4.10 of the text for Java code that detects prime numbers (this may vary depending on the edition you have).\
A static, isPrime(MyInteger) that returns true if the value is a prime number. Note that this method takes an object reference variable (rather than the value) as a parameter.
My problems come up in the static boolean isPrime method, stating that "/" and "%" are undefined for arguement type and in the main method in my if statement: isPrime() == true. It says to change it to static, but i already have a static boolean isPrime method and I'm supposed to have two isPrime methods according to my conditions. Thank you if you are able to help.
public class MyInteger {
public MyInteger(int value){
}
public static int getValue(){
int value = 997;
return value;
}
public boolean isPrime(){
int value = 997;
for (int i=2; i<=value/2; i++){
if(value % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrime(MyInteger value){
for(int i=2; i<=value/2; i++){
if(value%i == 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
MyInteger value = new MyInteger(MyInteger.getValue());
if (isPrime()==true && isPrime(value)==true){
System.out.println("Testiwng Instance method, is Prime");
System.out.println("isPrime: " + value + " is prime");
System.out.println("--------------------------------");
System.out.println("Testing Class method (That takes a reference variable) is Prime");
System.out.println("isPrime: " + value + " is prime");
}
else{
System.out.println("Testiwng Instance method, is Prime");
System.out.println("isPrime: " + value + " is not prime");
System.out.println("--------------------------------");
System.out.println("Testing Class method (That takes a reference variable) is Prime");
System.out.println("isPrime: " + value + " is not prime");
}
}
}
You don't have to go till the half of the number to check whether it is prime. You can have a loop that checks only the numbers from 2 to the square root of your number. See this - StackOverflow question about checking prime numbers
I believe you need something like this:
public class Main {
public static void main(String[] args) throws IOException {
Scanner inp = new Scanner(System.in);
int someValue = inp.nextInt();
MyInteger myInt = new MyInteger(someValue);
System.out.println("Testing instance method:");
System.out.println(myInt.isPrime());
System.out.println("Testing static method:");
System.out.println(MyInteger.isPrime(myInt));
}
}
class MyInteger {
private int value;
public MyInteger(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean isPrime() {
int sqrt = (int) Math.sqrt((double)value);
for(int i = 2; i <= sqrt; i++) {
if (value % i == 0) return false;
}
return true;
}
public static boolean isPrime(MyInteger myInt) {
return myInt.isPrime();
}
}
Here's a good reference for testing prime numbers What would be the fastest method to test for primality in Java?
Primarily, change your isPrime() to
boolean isPrime(long n) {
if(n < 2) return false;
if(n == 2 || n == 3) return true;
if(n%2 == 0 || n%3 == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1;
for(long i = 6L; i <= sqrtN; i += 6) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
Your value variable in the method you mentioned is of the type MyInteger, but you're trying to use it as an int. you probably want to use value.getValue() instead.
You should consider using class level variable to make use of constructor to initialize it.
Also in main() method you are trying to access non-static method (isPrime()), use it as value.isPrime().
In case you don't want to use class variable, make use of static getValue() method inside your static boolean isPrime(MyInteger value) method which solves your problem
Another way to check the prime number
public String isPrime(int number) {
if (number < 0) {
return "not a valid number";
}
if (number == 0 || number == 1) {
return "not a prime number";
}
if (number == 2 || number == 3) {
return "prime number";
}
if ((number * number - 1) % 24 == 0) {
return "prime number";
} else {
return "not a prime number";
}
}

Square number in java

I have to do the method, that I give a number in, if it is a Square number, it will get me true back
if it's not it will get me false back,
I wrote the code:
public class Aufgabe {
static boolean x;
public static boolean istQuadratzahl(int zahl){
int n = (int) Math.sqrt(zahl);
if (zahl%n == 0){
x = true;
}
else {
return x=false;
}
return x;
}
public static void main(String []args){
System.out.println(istQuadratzahl(6));
}
}
but when I give 6 or 8 in, it gives me true back, where did I go wonge here?
In your case, sqrt(6) is 2.44948974278. When you cast it to int it becomes 2. Of course, 6 % 2 = 0.
Try to check the result with:
if (zahl == n * n){
x = true;
}
This will do the trick:
public boolean isSquare(double zahl){
double m=Math.sqrt(zahl);
double n=(int)Math.sqrt(zahl);
if(m==n)
return true;
else
return false;
}
int sqrt = (int) Math.sqrt(inputNumber);
if(sqrt*sqrt == number) {
System.out.println(number+" is a perfect square number!");
return true;
}else {
System.out.println(number+" is NOT a perfect square number!");
return false;
}
Don't use a static variable. In fact, don't use a variable at all.
In addition, your logic is wrong. (int)Math.sqrt(12) == 3, 12%3 == 0, but 12 is not a square.
public static boolean istQuadratzahl(int zahl)
{
int n = (int) Math.sqrt(zahl);
if (n*n == zahl)
return true;
else
return false;
}
change the 'if' to this
if (zahl == n * n){

How to Update a Counter for Fibonacci using Recursion?

Here's the deal I want to count the recursive calls for a basic Fibonacci code. I already have it so the values will print out in column format but I don't know how to update the recCounter. I think I have to add recCounter++; Somewhere and I don't know where
public static int recursionFibonacci(int n) {
recCounter = 1;
return fibonacci1(n);
}
public static int fibonacci1(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}
You should increment the counter every time you call the function:
public static int fibonacci1(int n) {
recCounter++; // <<-- here
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci1(n-1) + fibonacci1(n-2);
}
}

Categories