Determine prime number by user input using recursive method - java

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;
}
}

Related

Java: Using Scanner to receive data and compare each of them

I'm writing a Java program to allow the user to input a numerator and a denominator and display them as a fraction e.g. 4/5. This should be in a continuous loop until the user enters a numerator that is 0. The program is to compare each fraction and determine whether they are the same and report the result e.g. 4/5 and 4/5 are equal, 4/5 and 6/9 are not equal.
I can't get the program to run properly and I don't know the reason. The program runs, but the result is wrong i.e. when the fractions are equal, the program prints otherwise. I've tried using an object array but it doesn't work either.
Below are my codes
Fraction class
import java.util.Scanner;
public class Fraction {
private int n, d;
private String sN, sD, sF;
public void readInput(){
Scanner kb = new Scanner(System.in);
System.out.println("Enter the numerator: ");
n = kb.nextInt();
System.out.println("Enter the denominator: ");
d = kb.nextInt();
while (d == 0){
System.out.println("Error. Denominator should not" +
" be 0. Please enter again: ");
d = kb.nextInt();
}
sN = String.valueOf(n);
sD = String.valueOf(d);
sF = (sN + "/" + sD);
}
public void writeOutput(){
if (d < 0){ // Check if d is negative
d = -(d);
n = -(n);
System.out.println("The fraction that you have entered is: " +
n + "/" + d);
System.out.println("");
}
else{
System.out.println("The fraction that you have entered is: " +
n + "/" + d);
System.out.println("");
}
}
public int getN(){
return n;
}
public int getD(){
return d;
}
public boolean isZero(Fraction x){
return n == 0;
}
public boolean isEqual(Fraction x, Fraction y){
return x.sF.equals(y.sF);
}
}
public class main
public class TestFraction{
public static void main(String[] args){
Fraction frac = new Fraction();
Fraction frac2 = new Fraction();
System.out.println("The program is looped around getting the" +
" numerator and denominator of a fraction" +
" and displaying them as a fraction.");
System.out.println("Enter a zero fraction (i.e. numerator = 0)"
+ " to end the program.");
System.out.println("");
frac.readInput(); // User enter 1st fraction
if (!frac.isZero(frac)){ // Check if 1st numerator is zero
frac.writeOutput(); // Print 1st fraction
while (!frac.isZero(frac)){
frac2.readInput(); // User enter 2nd fraction
if (!frac2.isZero(frac2)){ // Check for subsequent numerator
frac2.writeOutput(); // Print 2nd fraction
if (frac2.isEqual(frac, frac2))
System.out.println("These 2 fractions are equal.");
else
System.out.println("These 2 fractions are not equal.");
}
else{
System.out.println("You have eneded the program with a" +
" zero fraction.");
System.exit(0);
}
}
}
else{
System.out.println("You have eneded the program with a" +
" zero fraction.");
System.exit(0);
}
}
}
I've decided to convert the fractions into Strings so as to compare them, I couldn't think of any other ways of comparing. If there is a better way, please share. Would really appreciate the knowledge.
Thanks in advance!
You can override toString() for printing the fraction. Also, override equals() for equality testing (which requires we override hashCode(), too).
public static class Fraction {
protected int n, d;
public void readInput(Scanner kb) {
System.out.println("Enter the numerator: ");
n = kb.nextInt();
System.out.println("Enter the denominator: ");
d = kb.nextInt();
while (d == 0){
System.out.println("Error. Denominator should not" +
" be 0. Please enter again: ");
d = kb.nextInt();
}
}
#Override
public String toString() {
return n + "/" + d;
}
public int getN() {
return n;
}
public int getD() {
return d;
}
public boolean isZero(Fraction x) {
return n == 0;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() != this.getClass()) {
return false;
}
final Fraction other = (Fraction)obj;
return other.d == d && other.n == n;
}
#Override
public int hashCode() {
// Very simple hash
return toString().hashCode();
}
}
And in main:
Fraction frac1 = new Fraction();
Fraction frac2 = new Fraction();
// Only create 1 scanner
Scanner kb = new Scanner(System.in);
frac1.readInput(kb);
System.out.println(frac1);
frac2.readInput(kb);
System.out.println(frac2);
// No need for the checks for 0 in the denom since
// Fraction.readInput() guarantees it will not be 0
if (frac1.equals(frac2)) {
System.out.println("The 2 are equal.");
}
else {
System.out.println("The 2 are not equal.");
}

Prime Numbers in Java (return next prime when false)

public class PrimeNumbers {
public static void main(String[] args) {
int num = 6;
boolean isPrime = true;
for (int i = 2; i <= num - i; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
int nextPrime = num++;
{
while (isPrime = false) {
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" + "the next prime number is" + nextPrime(num));
}
}
}
I have tried to code in Java in order to find the next prime number while the previously returned is false, but I am really confused about how to proceed with "while" code. This is what I have tried until now:
You can create two functions: one (say, isPrime) to check if the number is prime or not and the second (say, nextPrime) to find the next prime. The logic in the second function will be quite straight forward: keep incrementing the number by 1 until isPrime returns true.
Note that you need to check only up to the square root of the number in order to determine if it is prime. Check https://en.wikipedia.org/wiki/Primality_test to learn more about it.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
if (isPrime(n)) {
System.out.println("It is a prime number");
} else {
System.out.println("It is not a prime number. The next prime number is " + nextPrime(n));
}
}
static boolean isPrime(int n) {
if (n == 1 || n == 0) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
static int nextPrime(int n) {
while (!isPrime(n)) {
n++;
}
return n;
}
}
A sample run:
Enter an integer: 10
It is not a prime number. The next prime number is 11
Another sample run:
Enter an integer: 11
It is a prime nmber
How about this snippet?
public static void main(String[] args) {
int number= 14; // will print the second SOUT statement with 17
if (isPrime(number)) {
System.out.println(number+ " is a prime number");
} else {
System.out.println(number+ " is not a prime number, " +
"the next prime number is " + nextPrime(number));
}
}
/**
* Check if the number is a prime number
* For 0 or 1 you can return false, for the rest if is divisible by each number
* You might want to throw an exception for the negative input
*/
static boolean isPrime(int number) {
if (number==0 || number==1) {
return false;
}
for (int i=2; i<=number/2; i++) {
if (number%i==0) {
return false;
}
}
return true;
}
/**
* Iterate the number by one until you find a prime number using the while cycle
*/
static int nextPrime(int number) {
int prime;
while (true) {
boolean isPrime = isPrime(++number);
if (isPrime) {
prime = number;
break;
}
}
return prime;
}
In order to find a prime number, you basically need a nested loop. So I'd recomend having your for loop INSIDE the while loop. OR you can have a do-while loop on the outside that keeps looping until you found a prime number.
Your code should look like this:
public class PrimeNumbers {
public static boolean check_prime(int num){
for (int i = 2; i <= num-i ; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args){
int num = 6;
boolean isPrime= true;
if(!check_prime(6)){
int nextPrime = num;
do{
nextPrime++;
if (check_prime(nextPrime)) {
isPrime = true;
break;
}else{
isPrime = false;
}
}while(!isPrime);
}
if (isPrime)
System.out.println("Is a prime number");
else
System.out.println("Is not a prime number" +"the next prime number is" + nextPrime);
}}}

I am trying to make a program which accepts two numbers and finds the prime, even and odd numbers in between

I am trying to make a program which will accept a starting number and ending number (int) and find the prime, even and odd numbers in between. I am not able to set my if and else conditions properly. It would be great if someone could even tell me a simpler method.
package proj2;
import java.util.Scanner;
public class Proj2
{
public void number(int sn,int en)
{
if (sn <= en)
{
int number = 2;
if (sn > number && sn % number != 0)
{
System.out.println(sn + " : " + "Prime");
number++;
sn++;
number(sn++,en);
}
else if (sn % 2 == 0)
{
System.out.println(sn + " : " + "Even");
sn++;
number(sn++,en);
}
else
{
System.out.println(sn + " : " + "Odd");
sn++;
number(sn,en);
}
}
}
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the starting number:");
int x = sc.nextInt();
System.out.println("Enter the ending number:");
int y = sc.nextInt();
Proj2 p = new Proj2();
p.number(x,y);
}
}
Being prime and odd are not mutually exclusive, your primality test is incorrect, and you are recursively calling number(). Instead use:
private boolean isPrime(int num){
// assuming positive ints
if( num <= 2 || num % 2 == 0)
return false;
for(int divisor = 3; divisor <= (int)Math.pow(num, 0.5); divisor+=2)
if( num % divisor == 0)
return false;
return true
}
public void number(int start, int end){
if( start <= end ){
for( int curr = start; curr <= end; curr++ ){
if( curr % 2 == 1 ) {
System.out.println(curr + " : Odd");
if(isPrime(curr))
System.out.println(curr + " : Prime");
} else System.out.println(curr + " : Even");
}
}

Generating emirps stop when a user enters a zero or negative integer.

I have created a program using Java that generates emirps by user input, but I need help on stopping the user when entering zero or a negative integer. I have tried many things but when I run the program with zero or a negative number it will go crazy and give me infinite amount of numbers. I would appreciate it if someone could help me on this.
Here is what I got so far...
import java.util.Scanner;
public class GenerateEmirps {
public static void main(String[] args) {
Scanner scanner = new Scanner (System.in);
System.out.print("Enter number of desired emirps: ");
int emrips = scanner.nextInt();
int count = 1;
for( int i = 2; ; i++){
if ((isPrime(i)) && (isPrime(reverseIt(i))) && (!isPalindrome(i))) {
System.out.print(i + " ");
if (count % 10 == 0) {
System.out.println();
}
if (count == emrips){
break;
}
count++;
}
}
}
public static boolean isPrime(int num){
for (int i = 2; i <=num / 2; i++){
if (num % i == 0) {
return false;
}
}
return true;
}
public static int reverseIt(int num){
int result = 0;
while (num != 0) {
int lastDigit = num % 10;
result = result * 10 + lastDigit;
num /= 10;
}
return result;
}
public static boolean isPalindrome(int num){
return num == reverseIt(num);
}
}
Solution:
You just need to test the input before you process it.
int emrips = scanner.nextInt();
if (emrips <= 0) { System.exit(0); }

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.");
}
}

Categories

Resources