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");
}
Related
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.");
}
}
So my professor had us do an assignment that asks the user for 5 numbers that are valid (51-99) and unique (non-repeating). I just can't figure out why my nested for loop inside the while loop is not incrementing the i, I suspect it is the break; but without that the for loop keeps looping. Any help would be awesome. Thank you.
public static void main(String[] args) {
int[] userArray;
userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
for (int i =0; i < userArray.length; i++) {
userArray[i] = count;
real++;
break;
}
} else {
System.out.println("That is not a valid number.");
}
}
}
public static boolean isValid(int a) {
if (a > 50 && a < 100) {
return true;
} else {
return false;
}
}
I got it guys! I just had to remove the for loop and put this in:
userArray[i] = count;
i++;
real++;
Thank you schmidt73 and everyone that helped!
int i=0;
while (real < 5) {
int count = entry.nextInt();
boolean aCount = isValid(count);
if (aCount == true) {
userArray[i++] = count;
real++;
} else {
System.out.println("That is not a valid number.");
}
}
I guess this is what you are trying to do.
First, you also need to test if the array contains the value you are trying to add (in validate). You could do something like
public static boolean isValid(int[] arr, int real, int a) {
if (a > 50 && a < 100) {
for (int i = 0; i < real; i++) {
if (arr[i] == a) {
return false;
}
}
return true;
}
return false;
}
Then your main method might be written like
int[] userArray = new int[5];
int real = 0;
System.out.println("Please print out 5 numbers between 50 and 100. ");
Scanner entry = new Scanner(System.in);
while (real < 5) {
int count = entry.nextInt();
if (isValid(userArray, real, count)) {
userArray[real++] = count;
} else {
System.out.println("That is not a valid number.");
}
}
System.out.println("The array contains: " + Arrays.toString(userArray));
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
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 !
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Please have a look at the following code
public class Prime
{
public static void main(String[]args)
{
int i = 2;
int counter = 0;
while(true)
{
if(counter==6)//Count still 6
{
break;
}
else
{
if(getPrimes(i)==true)
{
i++;
counter++;
System.out.println("Counter: "+counter);
}
else
{
System.out.println("No");
}
}
}
}
static boolean getPrimes(int num)
{
boolean result = false;
int i = 2;
while(true)
{
if((num%i) != 0) //if the number cannot be divided by any other number (except 1 and it self) it is prime
{
result = true;
System.out.println(num);
System.out.println("I is: "+i);
i=2;
break;
}
else //Not a prime. Repeat the process
{
result = false;
i++;
}
}
return result;
}
}
In here, I am trying to get all the prime numbers between 0-6. This is the test case to get thousands of prime numbers from a really big number. However, it is not showing the only primes, it is showing each and every number!
What am I doing here wrong? Please help!
try this answer...in ur loop
static boolean getPrimes(int num)
{
boolean result=true; // incase u gave 1 or 2 as input.....
int i = 2;
int mid=num/2;
while(i<mid)
{
if(num%i==0)
{
result=false; // not a prime and breaks...
break;
}
else
{
result=true; // the loop make result as true.....
}
i++;
}
return result;
}
I think you need something like this:
public void getPrimes(int a){
for(int i = 2; i < a; i++){
int inCounter = 0;
if(counter%i==0){
System.out.println("false");
inCounter++;
}
if(inCounter == 0){
System.out.println("Prime: "+counter);
}
}
}
Use a sieve, either Eratosthenes or Atkins
Here's the Eratosthenes implementation by Robert Sedgewick in Java:
http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html
I guess I found the solution. At least, I found the answer I need. Here is my answer
import java.math.BigInteger;
public class Problem7
{
public static void main(String[]args)
{
int i = 0;
int counter = 0;
while(true)
{
if(i>6)
{
break;
}
if(i>1)
{
String str = String.valueOf(i);
if (new BigInteger(str).isProbablePrime(i/2))
{
System.out.println(str);
counter++;
}
}
i++;
}
}
}
I guess this is the easiest way...
import java.util.Scanner;
class PrimeNumbers2
{
public static void main (String[] args)
{
Scanner scanner = new Scanner(System.in);
int i =0;
int num =0;
//Empty String
String primeNumbers = "";
System.out.println("Enter the value of n:");
int n = scanner.nextInt();
for (i = 1; i <= n; i++)
{
int counter=0;
for(num =i; num>=1; num--)
{
if(i%num==0)
{
counter = counter + 1;
}
}
if (counter ==2)
{
//Appended the Prime number to the String
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println("Prime numbers from 1 to n are :");
System.out.println(primeNumbers);
}
}
it will display all the prime number.
Find Prime number with minimum iteration
boolean IsPrimeNumber(int num) {
boolean isPrime = true;
if (num == 1 || num ==0)
isPrime = false;
else{
int limit = (int) Math.sqrt(num);
for (long i = 2L; i <=limit ; i++)
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime;
}