Suggestions to improve code about primes? - java

I wrote a code about primes and would hear your opinion or any suggestions how i can improve my code. I'm a beginner in Java.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
System.out.println("Please enter a number: ");
int zahl = s.nextInt();
if(zahl <= 0) {
System.out.println("Please enter a positive number without zero.");
return;
}
a = true;
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
if (a == true) {
System.out.println("Is Prim");
}
if (a==false){
System.out.println("Not a prim");
}
}

The easiest thing to do is the following
Instead of
for (int i = 2; i < zahl; i++) {
if (zahl % i == 0) {
a = false;
}
}
change the for loop the
for (int i = 2; i < Math.sqrt(zahl); i++)
If no numbers up to the square root divide zahl, then no numbers beyond the square root will divide it either (they would have been the result of earlier divisions).
Also, for outputing the answer you could do:
System.out.println(zahl + " is " + ((a) ? "prime"
: "not prime"));
That's using the ternary operator ?:

some hints :
You do
System.out.println("Please enter a positive number without zero.");
return;
the println suggests the user can enter a new value, but no, in that case better to say the number was invalid so you exit
When you do a = false; it is useless to continue, no chance for a to be back true
It is useless to try to divide by more than sqrt the number
It is necessary to try to divide by 2 but not by an other even number, so add 2 to i rather than 1
If if (a == true) false it is useless to check if (a==false)

Your code is good. I have made three small improvements:
The input asks at once (and not only after a bad input) for a
positive int.
The input is repeated until correct.
The for loop runs only up to sqrt(zahl) which is sufficient.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean a;
int zahl = 0;
while (zahl <= 0) {
System.out.println("Please enter a positive int without zero.");
zahl = s.nextInt();
}
a = true;
for (int i = 2; i <= Math.sqrt(zahl); i++) {
if (zahl % i == 0) {
a = false;
break;
}
}
if (a == true) {
System.out.println("Is Prim");
} else {
System.out.println("Not a prim");
}
}

Related

Trying to find the next prime number, not sure whats wrong. Java

im fairly new to Java and just cant figure out why my program is not working. Anything anyone can do to help would be appreciated!
public class LabOne {
public static void main(String[] args) {
System.out.println("Please input a number: \n");
int inputReceive = 44;
int nextPrime = inputReceive;
int n = 5;
boolean isprime=true;
do {
if(inputReceive <= 1)
isprime = false;
else if(inputReceive <= 3){
System.out.printf("%d \n",isprime);
return;
}else if( inputReceive % 2 == 0 || inputReceive % 3 == 0)
isprime = false;
while ((n*n)<inputReceive){
if (inputReceive % n == 0 || inputReceive % (n + 2) == 0)
isprime = false;
n = n+6;
isprime = true;
}
nextPrime++;
}while(isprime = false);
System.out.printf("Next prime number is %d",nextPrime);
}
}
output given would be 45 and thats not correct.
A few problems:
while(isprime = false);
That's assignment, not equality testing. Since you're assigning false, this won't loop.
n = n+6;
isprime = true;
You do this unconditionally.
Expansion to follow.
Ignoring things already pointed out, you perform all of your checks on inputRecieve and never update it. You only unconditionally update nextPrime and moreover never check its primeness. Here is how I would do it:
public static boolean isPrime(int x){
boolean result = true;
for(int i = 2; i<=Math.sqrt(x); i++){
if((x % i) == 0){
result = false;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please insert a number:");
int inputRecieve = sc.nextInt();
boolean notPrime = true;
while(notPrime){
if(isPrime(++inputRecieve))
notPrime = false;
}
System.out.println("Next prime number is: " + inputRecieve);
}

Java - Catalan numbers IllegalArgumentException and boolean to int problems

I am trying to write a program that takes an integer value (n) from the user, checks that it is greater than 0 and less than 30. If this is the case it calls my catalan numbers method and substitutes n in. If the inputted number is less than 0 or greater than 30 it should throw and IllegalArgumentException.
There doesn't seem to be a problem with the catalan numbers method, but there are when I try and call the catalan numbers method and input 'n' into it. All the problems are confined to the switch statement, where it will not accept the functions 'n.equals("quit"), (n>30), (n < 0), and it won't call my catalan numbers method.
Here is my code so far:
public class Exercise_3 {
public static long catalan(int n) throws IllegalArgumentException {
int res = 0;
// Base case
if (n <=1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan( n - i - 1);
}
return res;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Exercise_3 cn = new Exercise_3();
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
boolean n = scan.nextBoolean(); {
switch(n) {
if (n.equals("quit")) {
break;
}
else
case (n > 30):
throw IllegalArgumentException;
break;
case (n < 0):
throw IllegalArgumentException;
break;
case (0 < n <= 30):
int i = cn(n);
break;
}
System.out.println(i);
}
}
}
If anybody has any solutions to this I would be very grateful.
Your approach in using switch is, sorry for that, completely wrong. This is no JavaScript where you can pass the result of a Promise to a boolean. If you want to use Java, you have to learn a totally different thinking in solving problems. Switch is the worst choice to your problem. Try it with nested If-Statements instead.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter an integer greater than 0 and less than 30 or type 'quit' to exit.");
String input = scan.next();
if(!input.equals("quit")) {
int number = Integer.parseInt(input);
if(number < 0 || number > 30) {
throw new IllegalArgumentException("number out of range");
}
else {
int i = catalan(number);
System.out.println(i);
}
}
}

How to reject inputs that are non digit characters?

My professor assigned to write a prime number "finder". Where the number you input will display if it's a prime or even number, then display the next prime number. He wants us to give an error message when the wrong input is keyed in. I figured the negative integer portion is simple, but I cannot figure out the character input. Or if the character is not a digit. How would i block non numeric inputs?
Also, the system is supposed to exit at three CONSECUTIVE erroneous inputs. How would I reset the counter? The way i have written the program, if the user makes two errors but the next ones are acceptable, then make another error. (thus not being consecutive.) the program closes.
This is my first programing course so I'm not to savvy in it. Any help would be greatly appreciated.
Also, i have to use scanner, and the two methods.
/**
*
* #param n
* #return
*/
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer = 2;
int counter = 1;
boolean playAgain = false;
Scanner input = new Scanner(System.in);
Scanner reader = new Scanner(System.in);
Scanner in = new Scanner(System.in);
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
int n = input.nextInt();
{
//decide is negative
while ( n < 0){
//count counter
counter++;
//give error message
System.out.println("\nInvalid Input! Stike!");
//ask for input
System.out.print("\nEnter the integer value-> ");
//input answer
n = input.nextInt();
//decide is character
// if ( n != '.'){
//count counter
// counter++;
//give error message
// System.out.println("\nInvalid Input! Strike!");
// }
//decide if count three errors
if (counter == 3){
//display three errors message
System.out.println("Three Strikes! You're Out!");
//close program
System.exit(0);
}
}
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
} else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
{
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
answer = in.nextInt();
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
}
} while (playAgain != false);
}
}
import java.util.Scanner;
public class SOQ5B
{
public static boolean isPrime(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static int nextPrime(int n) {
n++;
isPrime(n);
while (isPrime(n) == false) {
n++;
isPrime(n);
}
int prime = n;
return prime;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int answer;
int counter = 0;
int n;
boolean playAgain = true;
boolean isNum;
boolean isNum2;
boolean continuePermitted = true;
Scanner input = new Scanner(System.in);
String s;
do {
//ask for input
System.out.print("\nEnter the integer value-> ");
s = input.nextLine();
isNum = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum = false;
}
}
if(isNum)
{
counter = 0;
n = Integer.parseInt(s);
//decide if prime
if (isPrime(n)) {
//display prime answer
System.out.println(n + " Is Prime");
//decide if even
}
else {
//display even answer
System.out.println(n + " Is Even");
}
//counter input
n++;
//while input is false
while (isPrime(n) == false) {
n++;
}
//display next prime
System.out.println(n + " Next prime");
do
{
continuePermitted = true;
//ask if you want to continue
System.out.println("\nPlay Again?\n\nEnter 1)Yes or 2)No ");
//input answer
s = input.nextLine();
isNum2 = true;
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
isNum2 = false;
}
}
if(isNum2)
{
answer = Integer.parseInt(s);
//if answer is 1)yes
if (answer == 1) {
playAgain = true;
//display play again and next input
System.out.println("\nPlay Again!");
}
//if answer is no
if (answer == 2) {
playAgain = false;
System.out.println("\nGoodbye!");
//close program
System.exit(0);
}
}
else
{
System.out.println("Incorrect response.");
continuePermitted = false;
//if answering the yes or no question incorrectly is part of the 3 strikes
//then uncomment the following lines of code
/*
counter++;
}
if(counter >= 3)
{
System.out.println("3 strikes you out");
System.exit(0);
*/
}
}while(!continuePermitted);
}
else
{
System.out.print("\nIncorrect input. Number must be a positive integer.\n");
counter++;
}
if(counter>=3)
{
System.out.println("3 strikes and you're out!");
System.exit(0);
}
} while (playAgain != false);
}
}
In the future, I recommend you research your questions on the internet before bringing the question here. There were several other places that could've easily answered your question.
Now as for your actual question, notice how I changed your code at the line that says s = input.nextLine()? What I did there is checked to see if each digit in the string was any number between and including 0-9. Not only was I able to check if they were all numbers, but I was also able to see if they were all positive too as you would have to put a - in order for it to be negative. Along with that, you also have a boolean that only works when the input is a positive number. If not, it checks 3 times to make sure your program doesn't mess up. Furthermore, I even commented out another section that allows the 3 strikes to include if answering the yes no question counts as a strike. If there any other questions, just ask and I will edit my answer.
You are trying to take input using Scanner class with
int n = input.nextInt();
If you enter a character in place of number here you will get java.util.InputMismatchException
What you can do is something like
try {
int n = input.nextInt();
} catch (InputMismatchException e) {
//handle the error scenario where the input is a character
System.out.println("Enter Valid Input");
}

How can I count the number of odd, evens, and zeros in a multiple digit number in Java?

Basically I need to write a program that takes user input up to and including 2^31 -1 in the form of an integer and returns the amount of odd, even, and zero numbers in the int. For example,
Input: 100
Output: 1 Odd, 0 Even, 2 Zeros // 1(Odd)0(Zero)0(Zero)
or
Input: 2034
Output: 1 Odd, 2 Even, 1 Zero // 2(Even)0(Zero)3(Odd)4(Even)
I'm pretty sure I'm over thinking it but I can't slow my brain down. Can anyone help?
This is the third iteration of the code, the first two were attempted with for loops.
import java.util.Scanner;
public class oddEvenZero
{
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int value;
int evenCount = 0, oddCount = 0, zeroCount = 0;
System.out.print("Enter an integer: ");
value = scan.nextInt();
while (value > 0) {
value = value % 10;
if (value==0)
{
zeroCount++;
}
else if (value%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
System.out.println();
System.out.printf("Even: %d Odd: %d Zero: %d", evenCount, oddCount, zeroCount);
}
}
Sorry, the code formatted weirdly in the textbox.
value = value % 10;
Probably the end-all-be-all of your problems.
If value is 2034, then value % 10 returns 4... and then assigns that value to value, you go through your if else block, then do 4/10 get 0, and exit the while loop without addressing the other 3 digits.
I suggest something more like this:
while (value > 0) {
if ((value%10)==0) {
zeroCount++;
}
else if (value%2==0) { //As per comment below...
evenCount++;
}
else {
oddCount++;
}
value /= 10;
}
Or, int thisDigit = value % 10, then replace value in your current if else block with thisDigit.
value = value % 10;
This statement will override your original value with a reminder i.e value % 10.
If value = 2034 and value % 10 = 4, then value = 4 which isn't what you want.
Instead use a temporary variable
int lastDigit = value % 10;
Then your code becomes;
while (value > 0) {
int lastDigit = value % 10;
if (lastDigit==0)
{
zeroCount++;
}
else if (lastDigit%2==0)
{
evenCount++;
}
else
{
oddCount++;
}
value = value / 10;
}
import java.util.Scanner;
public class oddEvenZero
{
public int[] convertStringArraytoIntArray(String[] sarray) throws Exception {
if (sarray != null)
{
int k= sarray.length-1;
int intarray[] = new int[k];
for (int i = 1; i < sarray.length; i++) {
intarray[i-1] = Integer.parseInt(sarray[i]);
}
return intarray;
}
return null;
}
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
String value;
System.out.print("Enter an integer: ");
value = scan.next();
String words[] = value.split("");
oddEvenZero obj = new oddEvenZero();
try{
int intarray[]= obj.convertStringArraytoIntArray(words);
int even_number =0;
int odd_number =0;
int zero_number =0;
for (int h: intarray)
{
if(h==0)
{
zero_number++;
}
else if(h%2==0)
{
even_number++;
}
else{
odd_number++;
}
}
System.out.println("even numbers are"+ even_number);
System.out.println("odd numbers are"+odd_number);
System.out.println("Zero numbers are"+zero_number);
}
catch(Exception ex)
{
System.out.println("Please enter number");
}
}
}
If some of you are still unable to figure this code out, I found this while searching around for a bit, and works just fine:
import java.util.*;
public class Java_1
{
public static void main (String[] args)
{
String string;
int zero = 0, odd = 0, even = 0, length, left = 0;
Scanner scan = new Scanner(System.in);
System.out.print ("Enter any positive number: ");
string = scan.next();
length = string.length();
while (left < length)
{
string.charAt(left);
if (string.charAt(left) == 0)
zero++;
else if (string.charAt(left) % 2 == 0)
even++;
else
odd++;
left++;
}
System.out.println ("There are: "+ zero + " zeros.");
System.out.println ("There are: "+ even + " even numbers.");
System.out.println ("There are: "+ odd + " odd numbers.");
}
}

Determine prime number by user input using recursive method

I need to create a program in Java that determines if a number is prime.
The user should enter any number, and the program will determine if it's prime or not, and display "not prime" or "prime." My code now compiles and runs but it always says a number isn't prime even if it is.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int constant = 0;
int variable = 0;
System.out.println("Enter a Number to test if Prime or Not");
constant = input.nextInt();
variable = constant;
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println(+answer);
if (answer == 1)
{
System.out.println(+constant + " is a prime number.");
}
else
{
System.out.println(+constant + " is NOT a prime number.");
}
}
public static double testPrime(int number, int divide)
{
double prime = 0.0;
prime = number%divide;
if (prime > 0 && divide != number)
{
return testPrime(number, divide - 1);
}
else
{
return prime;
}
}
}
if (prime > 0 && divide != number)
This will never be true. Because your divide and number are always equal.
See that you have assigned variable=constant and that's what you pass to the method
constant = input.nextInt();
variable = constant;
answer = testPrime(constant, variable);
That said, you need go so complex to find out if a number is prime or not. Check the web for simple algorithms. See http://www.mkyong.com/java/how-to-determine-a-prime-number-in-java/ for example.
Not the answer as the OP wants recursion (homework I guess).
You need to only go till the square root of n to see if it has a divisor (divisor besides self will be < sqrt(n))
boolean isPrime(int n) {
if(n % 2 == 0)return false;
int till = (int)java.lang.Math.pow(n, 0.5); //(int)n / 2;
for(int i= 3;i<till;i+=2) {
if(n % i == 0)
return false;
}
return true;
}
I see you want recursion for this, so I converted tgkprog's answer to a recursive method (although his is definitely more efficient). Additionally, I think you may want to return a prime factor if the input isn't prime? I'm just speculating this judging from the OP's return value of a double instead of a boolean. Mine will return an int though, because returning a double is silly.
int isPrime(int n){ //starter function
if(n<=1) return n; //sanity check for weird inputs
if(n % 2 == 0) return 2; //2 is a prime factor
int start = (int)java.lang.Math.pow(n, 0.5);
return isPrime(n,start-(start%2)); //makes start odd if it wasn't already
}
int isPrime(int n, int testval){ //recursive function
if(testval<=1) return 1; //n is prime, return n since it has no prime factors
if(n % i == 0)
return i; //found a prime factor!
return isPrime(n,i-2);
}
with recursion
import java.util.Scanner;
public class PrimeRecursion
{
static int dbg;
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter non 0 if you want debug :");
dbg = input.nextInt();
long constant = 3;
long variable = 0;
while(true){
System.out.println("Enter a Number to test if Prime or Not (1 to exit)");
constant = input.nextLong();
if(constant < 3){
if(constant == 2){
System.out.println("2 is a special prime");
}
return;
}
if(constant % 2 == 0){
System.out.println(constant + " is NOT a prime number, even number.");
}else{
variable = (long)Math.pow(constant, 0.5);
variable = (variable % 2 == 1) ? variable : variable + 1;//odd number
double answer = 0.0;
answer = testPrime(constant, variable);
System.out.println("End answer : " + answer);
if (answer == 1){
System.out.println(+constant + " is a prime number. answer : " + answer);
}
else{
System.out.println(constant + " is NOT a prime number.answer : " + answer);
}
}
System.out.println();
}
}
static double testPrime(long number, long divide)
{
double prime = 0.0;
prime = (double)number / divide;
if(dbg > 0){
System.out.println("Debug number " + number + " | divide " + divide + " |prime : " + prime + " | Math.abs(prime) " + Math.abs(prime));
}
if (prime == ((long)prime))//whats the best way to do this?
{
//divided evenly
return divide;
}
else{
return testPrime(number, divide - 2);
}
}
}
the recursive function for me goes like-Correct me if i am wrong.Thank you.calling statement >Boolean b=isPrime(number,number-1);
recursive function-
void isPrime(int p,int d);
{
int prime=p%d;
if((p==0&&d>1)||p%2==0)
return true;//that the number is not prime
if(d==1)
return false;
else
return isPrime(p,d-2);//calls the function again
}
Well I am directly giving you all the code instead of writing snippet. Hope you all may like this one as I have tried my best to make it as simple as possible.
The code is :>
import java.util.*;
class Prime_Number
{
static int c=0;
public static void main(String args[])
{
int n,i,sq=0;
Scanner in=new Scanner(System.in);
Prime_Number ob=new Prime_Number();
System.out.print("Enter a no.:>");
n=in.nextInt();
i=n;
sq=(int)(Math.sqrt(n));//square root is been taken since a no. cannot have factors greater than its square root
int k=ob.prime_Chk(n,i,sq);
if(k==1)
{
System.out.println("Prime");
}
else
{
System.out.println("Non-Prime");
}
}
public int prime_Chk(int g,int i,int sq)
{
if(i==sq)
{
return c;
}
else
{
if(g%i==0)
{
c++;
}
i--;
return(prime_Chk(g,i,sq));
}
}
}
Well in the prime() I have taken int i , int sq and int g as arguments.Instead of those if you wish then you can take other variables also.
import java.util.Scanner;
public class HW8R_T03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("Enter number: ");
int n = sc.nextInt();
int simple = prime(n,n-1);
System.out.println(simple==1 ? "prime" : "not prime");
}
static int prime(int x, int y){
int div = 1;
if (y==0 || y==1){
return div;
}
if (x%y==0){
div = y;
} else {
div = prime (x, --y);
}
return div;
}
}

Categories

Resources