Writing a program that determines a prime number - java

I'm trying to write a program that asks the user to enter a number, then I need to create a method called isPrime to create the calculation and print out the result in main. I'm sure it's something small that I'm missing, but I can't get it to produce an accurate result.
public static void main(String[] args) {
System.out.print("Enter number: ");
int num = s.nextInt();
if (isPrime(num) == true) {
System.out.println("Number is prime");
} else if (isPrime(num) == false) {
System.out.println("Number is not prime");
}
}
public static boolean isPrime(int num){
for(int i = 2; i <= num/2; i++) {
if (num%i != 0) {
return true;
}
}
return false;
}

Use an if and else (don't retest your boolean condition in the first case). And don't test for == true in an if. This
if(isPrime(num) == true)
{
System.out.println("Number is prime");
}
else if(isPrime(num) == false)
{
System.out.println("Number is not prime");
}
Should just be
if (isPrime(num)) {
System.out.println("Number is prime");
} else {
System.out.pritnln("Number is not prime");
}
or even something like
System.out.print("Number is ");
if (!isPrime(num)) {
System.out.print("not ");
}
System.out.println("prime");
If you want to put the braces on their own lines go ahead. As for your isPrime method; you have your return conditions reversed (and the test as well). Also we can optimize it a bit. Unroll the first even test, because then we can skip every other element. Also we only need to test to the square root of the input number. Like,
public static boolean isPrime(int num) {
if (num == 2) {
return true; // two is prime.
}
if (num < 1 || num % 2 == 0) {
return false; // all other even numbers are not prime.
}
for(int i = 3; i <= Math.sqrt(num); i += 2) {
if (num % i == 0) {
return false;
}
}
return true;
}

The isPrime(int num) method may need to check if num % i == 0 instead of if num % i != 0 because many non-prime numbers will pass the condition and return true.
As an example, if isPrime(9) is called, the conditional will check if 9 % 2 != 0, which is true, and the method will say that 9 is prime when it's not.
As a result, you could try changing the method to something like this:
public static boolean isPrime(int num)
{
for(int i = 2; i <= num/2; i++)
{
if (num%i==0)
{
return false;
}
}
return true;
}

You should change your "if (num%i!=0)" condition to if(num % i == 0)
See the following code:
public class Prime {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num % i == 0)
{
flag = true;
break;
}
}
if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}

Related

I have a question with the logic of a program that checks if a number is prime. (I have to use 3 methods)

I'm having trouble implementing 3 methods to create a program that checks if a number is prime. When I call my methods and run the program the only value that shows is 0. I'm assuming this has to do with variables or logic in my methods
I have tried using different variables to store user input then using that variable as an argument in my methods.
package practice;
import java.util.Scanner;
public class Practice {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
//int result = 0 ; //stores number user picks
int numPicked = 0; //
int endResults = 0; //stores result of calculation
// Calling methods
isPrime(numPicked);
pickedNum(numPicked);
results(endResults);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked){
if (numPicked <= 1) {
return false;
}
for (int i = 2; i <= numPicked; i++) {
if (numPicked % i == 0) {
return false;
}
}
return true;
}
// Method that asks user for a positive integer
public static int pickedNum (int userNumbers){
Scanner s = new Scanner(System.in);
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked){
if(numPicked == 0 && numPicked != 1 ){
System.out.println( numPicked + " is a Prime Number");
}
else{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
}
I need to fix the logic within my methods to be able to call them correctly.
I did some correction in your code and working version is below. There is a lot of things that should be also changed but I tried to make your program working without big changes.
So first of all, You had 2 Scanners so I deleted one of them. Second thing your isPrime method was not working correctly so I replace it with working version. Other thing was that you called isPrime before loading value which was main problem that you always got 0. Other thing is that java is pass by value it means that if you put int as argument and you modify it inside method you still have old value so you have to assign returned value to your value again
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
//int result = 0 ; //stores number user picks
int numPicked = 0; //
boolean isPrime = false;
// Calling methods
numPicked = pickedNum();
isPrime = isPrime(numPicked);
results(numPicked, isPrime);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked) {
if (numPicked == 2)
return true;
if (numPicked < 2 || numPicked % 2 == 0)
return false;
for (int i = 3; i * i <= numPicked; i += 2)
if (numPicked % i == 0)
return false;
return true;
}
// Method that asks user for a positive integer
public static int pickedNum()
{
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked, boolean isPrime)
{
if(isPrime)
{
System.out.println( numPicked + " is a Prime Number");
}
else
{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
package test;
import java.util.Scanner;
public class Practice {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
int numPicked = 0; //
Commented out endResults as it currently has no functionality.
//int endResults = 0; //stores result of calculation
Added a Boolean to record whether isPrime is true or false
boolean isPrime;
numPicked now stores the returned value of the pickedNum method and it takes no parameters.
// Calling methods
numPicked = pickedNum();
isPrime = isPrime(numPicked);
Pass the Boolean value to the results method, true or false.
results(numPicked, isPrime);
}
// Method to check if numbers are prime
public static boolean isPrime(int numPicked)
{
if (numPicked <= 1) {
return false;
}
Removed <= with just less than. This is as if numPicked equals its own value it will return false. In reality a prime number can only be divided by itself so you just need to check the numbers less than it.
for (int i = 2; i < numPicked; i++) {
if (numPicked % i == 0) {
return false;
}
}
return true;
}
// Method that asks user for a positive integer
public static int pickedNum ()
{
Scanner s = new Scanner(System.in);
System.out.println("Type a positive number that you want to know if it's prime or not.");
int numPicked = s.nextInt();
return numPicked;
}
// Method that displays result of calculation
public static int results (int numPicked, boolean isPrime)
{
Checks if isPrime is true.
if(isPrime)
{
System.out.println( numPicked + " is a Prime Number");
}
else
{
System.out.println(numPicked + " is Not a Prime Number");
}
return numPicked;
}
}

Prime Factoring in Java - Intro Programming

Original: So for my intro to programming class, we have to find the prime factors of a range of numbers that the user inputs (i.e. 59-65). The issue with a lot of the solutions here is that they use things that we haven't discussed in class like arrays, continue, etc. It's a pretty basic class. As for the requirements, we have to use a primeFact method/function that we call in the first for loop. She instructed us to use a while and for loop in the method to get the prime factors but everytime I think I have something, it doesn't come out right. Any help is really appreciated and my code is below. I really only need help with the method portion with the algorithm for finding the factors.
Edit: Here is the final solution that I turned in. It works and will give all prime factors of all numbers in a given range of numbers.
import java.util.Scanner;
public class PrimeFact {
public static void main(String[] args) {
int start, stop;
//Get input
Scanner input = new Scanner(System.in);
System.out.println("Please enter then two values with the lower value first");
start = input.nextInt();
stop = input.nextInt();
input.close();
//Displays for the start of the loop
System.out.println("Starting value (at least two digits): "+start);
System.out.println("Ending value (at least two digits): "+stop);
System.out.println("Prime factors for numbers between "+start+" and "+stop);
//Loop for the prime factors
for (int num = start; num <= stop; num++) {
primeFact(num);
}
}
// Method for Prime Factoring
public static void primeFact(int num) {
int divisor = 2;
System.out.print(num+" = ");
while (num>1) {
if ((num%divisor) == 0) {
System.out.print(divisor+" x ");
num=num/divisor;
} else {
divisor++;
}
}
System.out.print("1");
System.out.println();
}
}
public static void primeFact(int num) {
System.out.print(num+" = ");
for(int i=2;i<num;i++)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
for(int i=2;i<num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
//if u want use while replace the for loop like
public static void primeFact(int num) {
System.out.print(num+" = ");
int i=2;
while(i<num)
{
if(num%i==0)
{
if(isPrime(i))
{
System.out.println("Prime Factor for "+num+" is:"+i);
}
}
i=i+1;
}
if(num==2)
System.out.println("Prime Factor for "+num+" is:"+num);
}
static boolean isPrime(int num){
int i=2;
while(i<num)
{
if(num%i==0)
{
return false;
}
i=i+1;
}
return true;
}
you're method is pretty close to a solution. but your while loop is invalid.
remember it should be like this:
while(<boolean statement>){
//code here
}
I will reference the variable we are checking "primality" for as "num"
here's how to check for factors with a while loop:
//remember, num is given to us in the parameters of primeFact(int num).
boolean isPrime = true; //we are optimistic.
//we start at 2 because everything is divisible by one
int posFact = 2; //short for "possible factor"
while(posFact < num){ //this will start at 2, and go to 1 less than num
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
posFact++; //increments posFact up by 1
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}
We can do the exact same thing with a for loop:
//remember, num is given to us in the parameters.
boolean isPrime = true; //we are optimistic.
for(int posFact = 2; posFact < num; posFact++){ //posFact's initialization and incrementation was moved here.
if(num % posFact == 0){ // "%" gives us remainder
isPrime = false; // we now know it's not prime
System.out.println("The number " + posFact + " is a factor of " + num + ".");
}
}
if(isPrime){ //This will only be true if the number is prime
System.out.println("The number " + num + " is prime!");
}

A loop for checking prime number

package pureTest;
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test3 {
public static void main(String[] args) {
/* Enter your code here. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 2; i< n; i++){
if( n <= 3){
System.out.println("Prime");
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}else{
System.out.println("Prime");
}
}
}
}
the input of 7; the out put is repetitions of Prime:
7
Prime
Prime
Prime
Prime
Prime
Just wondering why the if condition doesn't work out here.
your code will print prime until it finds divisor !
for (int i = 2; i< n; i++){
if( n <= 3){
System.out.println("Prime");
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}else{
System.out.println("Prime"); --> this line will be printed every time in your loop!
}
}
Also you don't need to iterate till n, as after n/2 there would be no number which can divide n :-)
Check this code...
private static boolean checkPrime(int n) {
int i = 2;
while(i<=n/2){
if(n%i++ == 0){
return false;
}
}
return true;
}
Your else clause is wrong. It prints "Prime" each time n is not divisible by i. It will even print prime for non prime inputs (for example, it will print "Prime" for 21 before printing "Not Prime", since 21%2 != 0).
Change your loop to something like :
for (int i = 2; i < n; i++) {
if( n <= 3){
System.out.println("Prime");
return;
} else if(n%i == 0){
System.out.println("Not Prime");
return;
}
}
System.out.println("Prime");
public static void main(String[] args) {
/* Enter your code here. */
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i< n; i++){
if( n <= 3){
break;
}else if( n%i ==0){
System.out.println("Not Prime");
break;
}
}
if (isPrime) {
System.out.println("Prime");
} else {
System.out.println("Not prime");
}
}
If you want to simply check in the main function the above is ok. If you want to do that well try the following:
public static void main() {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (isPrime(n)) {
System.out.println("Prime");
} else {
System.out.println("Not prime");
}
}
boolean isPrime(int n) {
if (n < 2) {
return false;
if (n == 2)
return true;
if (n%2 == 0)
return false;
for (int i = 3; i*i<=n; i+=2){
if (n%i == 0)
return false
return true;
}
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 2; i< n; i++){
if(n%i==0) {
System.out.println("Not Prime");
isPrime=false;
break;
}
}
if(isPrime) {
System.out.println("Prime");
}

Error in finding a integers factor by a method

My program seems to work with numbers '25, 223, and 11" but i have no idea why it stops when i enter the numbers 10 or 100. Any ideas? Any help on this matter will be greatly appreciated-thank you in advance.
*****Source Code*****
import java.util.Scanner;
public class hw_5 {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num;
boolean primeTest;
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num != -1) {
primeTest = calcPrime(num);
if(!primeTest) {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return true; // If number is divisible by any number, return true.
}
return false; // If loop exits (means, number was not divisible by any number), return false.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
}
import java.util.Scanner;
public class Test {
public static boolean calcPrime(int num) {
for(int i = 2; i < num; i++) {
if(num % i == 0)
return false; // If number is divisible by any number, return false.
}
return true; // If loop exits (means, number was not divisible by any number), return true.
}
public static void printFactors(int num) {
int nFactors = 0;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
System.out.println(num+" is divisible by "+i);
nFactors++;
}
}
System.out.println(num+" has "+nFactors+" factors");
}
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
int num = 0;
boolean primeTest = false;
while(true) {
System.out.print("Enter an integer value: ");
num = inputReader.nextInt();
if(num == -1)
break;
primeTest = calcPrime(num);
if(primeTest)
System.out.println(num+" is prime.");
else {
System.out.println(num+" is not prime.");
printFactors(num);
}
}
}
}
Your prime test is wrong :
public static int calcPrime(int number) {
int primer = number % 2;
return primer;
}
It just tests if the number is odd.
Below method returns true if it is a prime number ,
boolean isPrime(int n) {
//check if n is a multiple of 2
if (n%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=n;i+=2) {
if(n%i==0)
return false;
}
return true;
}
You could add the numbers to the list and get the their values on iterating back

Prime number required by user in Java

I want to display the prime number required by the user. For example, if the user wants 3rd prime, I will display 5. I have the following java code.
import java.util.Scanner;
public class Prime {
private static Scanner scanner;
public static void main(String args[]) {
//get input till which prime number to be printed
// System.out.println("Enter which prime number to be printed: ");
// scanner = new Scanner(System.in);
// int limit = scanner.nextInt();
int count = 0;
int number = 2;
//System.out.println("Printing prime number from 1 to " + limit);
while(count<=3)
{
if(isPrime(number)){
count++;
// System.out.println(count);
}
number++;
}
if(count == 3)
System.out.println("10001 prime is "+number);
}
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false;
}
}
return true;
}
}
When i run it, I am not able to gett any output. Where am i going wrong?
PS: For time being, I am running the loop only until 3.
You have while(count <= 3) so when you exit the loop, count == 4.
Therefore, your if(count == 3) is never entered and nothing is printed.
Anyways the better solution would be
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(2);
arr.add(3);
int counter = 4;
while(arr.size() < inp) {
if(counter % 2 != 0 && counter%3 != 0) {
int temp = 4;
while(temp*temp <= counter) {
if(counter % temp == 0)
break;
temp ++;
}
if(temp*temp > counter) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp-1));
}
}
Here is corrected code that works.
public class Main {
public static void main(String args[]) {
//Returns fourth prime number
System.out.println(getPrimeNumber(4));
}
public static int getPrimeNumber(int order) {
int currentOrder = 1;
int currentNumber = 1;
while (currentOrder < order) {
currentNumber++;
if (isPrime(currentNumber)) currentOrder++;
}
return currentNumber;
}
public static boolean isPrime(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
There was no need to start your counter at 0 and it mathematically wrong to start with number 2 ! Just begin with order and currentNumber initialized at 1 and if first prime number is what your user is looking for, no loop will be required !
Also, your loop condition after correct variable initialization was corrected from "<=" to "<".
That's all !

Categories