Find Prime Numbers based on user input [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have these two methods that i am using to find prime numbers based on user input, i have a method called isPrime that logically should return true if a number is prime, however it always return true no matter what the number is?
I realise there are plenty of answers similar to my query but none have helped so far.
public static void userPrimes(){
int[] tempPrimes = new int[49];
int primesFound = 0;
//Input Amount of numbers to be analysed
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
//Input Values
for(int i = 0; i<initial.length; i++){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number at position:" + (i+1)));
if (initial[i] > 49){
initial[i] = Integer.parseInt(JOptionPane.showInputDialog("Numbers cannot be greater than 49, Try again:"));
}
}
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;
}
}
int[] finalPrimes = new int[primesFound];
for (int i=0;i<finalPrimes.length;i++){
finalPrimes[i] = tempPrimes[i];
System.out.print(finalPrimes[i] + " ");
}
}
//checks whether an int is prime or not.
static boolean isPrime(int n) {
for(int j = 2; j < n; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}

You have some problems in your code:
1.
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog("Enter Amount of numbers to be checked")) -1];
The array should be in length of the amount that the user entered, not minus 1
2.
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
primesFound++;}
You should put the primes in the temp primes array in tempPrimes[primesFound]
Also, your final loop is not useful.You can do the printing in the previous loop

Your isPrime function is fine but as performance wise is concerned you need to iterate till half of the number rather than iterating till number
boolean x = isPrime(13);
System.out.println(x);
static boolean isPrime(int n) {
for(int j = 2; j <= n/2; j++) {
if(n % j == 0) {
return false;
}
}
return true;
}
returns true and passing 14 returns false..it works perfect here..
might be the problem is with your loop code which is calling this method

modify this line by by removing -1
no need to do minus 1 as it reduces the no of input to user by one .
if user inputs amount as 3 then -1 makes him to enter only 2 numbers. so make it as below
int[] initial = new int[Integer.parseInt(JOptionPane.showInputDialog
("Enter Amount of numbers to be checked"))];
use only one loop as below to print all prime numbers
for(int i = 0; i<initial.length; i++){
if (isPrime(initial[i]) == true){
tempPrimes[i] = initial[i];
System.out.println(tempPrimes[i]);
}
}

Related

Array Index Out Of Bounds Exception Java Prime Numbers [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I've been trying to dive into java development and have gone for a relatively easy problem of finding prime numbers, however, I keep getting errors and can't see what I've done wrong, any help?
I've been toiling over my computer for an infuriating while and have tried everything, even rewriting the code from beginning
public class HelloWorld{
public static void main(String []args){
int[] check = {2};
//cycle through numbers 1-100
for (int i = 1; i < 100; i++) {
//cycle through numbers to be checked against i
for (int x = 0; x < 101; x++) {
//check if the current itteration of i has no multiples
if (i%check[x] == 0) {
check[i] = i;
} else {
// print any prime numbers
System.out.print(i);
check[i] = i;
}
}
}
}
}
The immediate cause of your error is that you defined the check[] array to have a size of 1, but you are trying to access elements higher than that, which don't exist. However, I don't think that you really need that array here. Consider this version:
for (int i=2; i < 100; i++) {
boolean match = true;
for (int x=2; x <= Math.sqrt(i); x++) {
if (i % x == 0) {
match = false;
break;
}
}
if (match) {
System.out.println("Prime number: " + i);
}
}
Note that the inner loop in x only needs to go as high as the square root of the outer i value. This is because any value greater than sqrt(i) can't possible divide it.
It is because your array has length 1
and you are trying to access out of bound indexes. In case you are lopping 0 to 101 You can initialize your array like this int [] check =new int [101]

Efficient Prime Number Computing Program Java

So I was trying to make a prime number calculator in java that goes from 1 up to the upper limit of the range given by the user and prints out all of the primes.
One way of approaching this was by simply using a nested for loop and testing divisibility for every number in the range by all of the numbers less than it.
However, I figured it would be more efficient to only test prime numbers to avoid repeated factors and speed up the program.
For example, if the number we were on was 16, rather than testing if it's divisible by 2,3,4,5,...14,15,16, I could only test out 2,3,5,7,11,13 and stop once a factor is found.
So I tried to make an array to store all of the primes found so far and only use those values to test for the next number.
Here's my code, I can't figure out why it's not working
Scanner sc = new Scanner (System.in);
System.out.print ("Enter the upper limit: ");
int high = sc.nextInt();
boolean isPrime = true;
int[] primearray = new int[0];
for (int num = 1; num <= high; num++)
{
for (int x: primearray)
{
if (num%x==0)
{
isPrime = false;
break;
}
}
if (isPrime == true) {
int size = primearray.length;
primearray = new int[size+1];
primearray [size] = num;
System.out.println (num);
}
}
First of all, 1 isn't prime. By starting your outer loop at 1, your prime array ends up with 1 in it and everything else will then test as not prime. Start your outer loop at int num = 2.
Second, you aren't copying over the existing known primes when you expand primearray. You can use
primearray = Arrays.copyOf(primearray, size+1);
which will make a new array with all the old contents copied and space for one more value.
Finally, you might want to check out the Sieve of Eratosthenes. A careful implementation of that algorithm will be more efficient than your current algorithm, which requires an expensive array reallocation every time you find a prime. You can use a BitSet to keep track of the flags that the sieve needs.
You have wrong in logic
boolean isPrime = true;
this variable should be declared in for loop, let 's imagine, if you find out 4 is not prime then isPrime = false, then you check 5 but there is not any code block that set isPrime = true.
And this block:
if (isPrime == true) {
int size = primearray.length;
primearray = new int[size+1];
primearray [size] = num;
System.out.println (num);
}
You created new array of prime number, primearray with size increased by 1, so primearray does not contain any old prime number, that will make wrong while checking prime. So you need to copy old prime numbers to new array.
And because the prime numbers start by 2, so your code should be:
Scanner sc = new Scanner(System.in);
System.out.print("Enter the upper limit: ");
int high = sc.nextInt();
int[] primeArray = new int[0];
for (int num = 2; num <= high; num++)
{
boolean isPrime = true;
for (int x : primeArray)
{
if (num % x == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
primeArray = Arrays.copyOf(primeArray, primeArray.length + 1);
primeArray[primeArray.length - 1] = num;
System.out.println(num);
}
}
You should use a Sieve of Eratosthenes to find primes, rather than testing each number for divisibility; that method is far slower than sieving. Here is an implementation of sieving from my blog:
public static LinkedList sieve(int n)
{
BitSet b = new BitSet(n);
LinkedList ps = new LinkedList();
b.set(0,n);
for (int p=2; p<n; p++)
{
if (b.get(p))
{
ps.add(p);
for (int i=p+p; i<n; i+=p)
{
b.clear(i);
}
}
}
return ps;
}
As you say the key simplification is to only test primes when you find the next prime. For example:
public class PrimeGenerator {
private long current = 1;
private final List<Long> primes = new ArrayList<>();
public long next() {
do {
current++;
} while (primes.stream().anyMatch(n -> current % n == 0));
primes.add(current);
return current;
}
public LongStream stream() {
return LongStream.generate(this::next);
}
}
This records each prime as it is generated.
You can generate get all primes to a certain value with
generator.stream().takeWhile(p -> p < value)...
Previous answers already explains what is wrong with your code.
I just want to share another approach which is more efficient. The sample implementation is as per below. Basically, once we know x is prime number, we also know i*x is NOT a prime number. Further reading and visualization is available here
public int countPrimes(int n) {
if (n == 0 || n == 1) return 0;
int count = 0;
boolean[] check = new boolean[n+1];
for (int i = 2; i < n; i++) {
if (check[i]) continue;
for (int j = 1; j <= n / i; j++) {
check[j * i] = true;
}
count++;
}
return count;
}

How to add and print prime numbers [closed]

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 6 years ago.
Improve this question
The idea is to type two numbers in the command line. The first being the start and the second being the number of prime numbers after the first number are displayed. For instance if the input was 16 3 the output would be 17 19 23
These numbers would be stored into an array. I've been trying many different things but they haven't worked so far.
I only have this right now
{
public static void main (String[] args)
{
int start =Integer.parseInt(args[0]);
int count =Integer.parseInt(args[1]);
int[] prime = new int[count];
public static boolean check(int a)
{
if (a%2==0)
return false;
for(int i=3;i*i<=a;i+=2)
{
if(a%i==0)
return false;
}
return true;
}
}
Your check function is great. What you need is just a while loop to add prime number to prime[]
public static void main (String[] args)
{
int start =Integer.parseInt(args[0]);
int count =Integer.parseInt(args[1]);
int[] prime = new int[count];
int i = 0;
while (i < count){
if(check(start)){
prime[i] = start;
i++;
}
start++;
}
for (int p : prime){
System.out.println( p);
}
}
If you want a program to do something N times, you can use a loop.
Since this feels like HW I will provide an analogous problem. Count N odd numbers:
int numbersToCount = 5;
int count = 0;
int start = 1;
while (count < numbersToCount) {
if (start % 2 == 1) {
count = count + 1;
// opportunity to print number you are interested in
}
start = start + 1;
}

This program in java doesn't stop executing [closed]

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 8 years ago.
Improve this question
I have written this java program for sorting some numbers. But it doesn't stop executing. Can you help me with it?
package inplacesort;
import java.util.*;
public class InplaceSort
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
Vector <Integer> intList = new Vector <Integer> ();
//getting the numbers from the user
char ans = 'y';
while (ans == 'Y' || ans == 'y')
{
System.out.print("Enter a Number: ");
intList.addElement(console.nextInt());
System.out.print("Do You Want to Continue?(Y/N)");
ans = console.next().charAt(0);
}
System.out.println("Before Sorting the Numbers: " + intList);
for (int i = 1; i < intList.size(); i++)
{
int j = i - 1;
while (j > 0 && intList.elementAt(i) < intList.elementAt(j))
{
j--;
}
for (int k = intList.size() - 1; k >= j; k--)
{
intList.insertElementAt(intList.elementAt(k),k + 1);
}
intList.insertElementAt(intList.elementAt(i+1),j);
intList.removeElementAt(i+1);
}
System.out.print(intList);
}
}
Your problem is with intList.size() in the k & i loops. This is not be as what you would expect it. When I debugged your code the value of k was 425996.
Edit :
When i debugged it more I saw that because of you mutating the vector within it self it keeps increasing in size. If you let your program run for a few minutes you will get out of memory error.
Please don't mutate the object you are looping though it. Either make a copy of it and the loop though one of them and mutate another or start with a fresh one & keep adding the values to it while looping over the older one.
System.out.println("Before Sorting the Numbers: " + intList);
List<Integer> sortList = new ArrayList<Integer>();
int minVal;
int index=0;
int size = intList.size();
for (int i = 0; i < size; i++)
{ minVal=Integer.MAX_VALUE;
for (int j = 0; j < intList.size(); j++)
{
if(intList.get(j) < minVal){
index=j;
minVal=intList.get(j);
}
}
intList.remove(index);
sortList.add(minVal);
}
System.out.print("After Sorting the Numbers: "+ sortList);
The reason is because your value for j is ALWAYS 1 less than the value for i. Therefore, infinite while loop.

there is no output on calculating prime number

i want to print first 100 prime numbers. so, i created an array of int 100. I added first prime, bag[0] = 2, then for the following numbers, I tried to write an algorithm. It will start from 3 and goes on until array is full. Every number is decided to be if it is prime by whether it is divisible by the previous elements in array and if it is prime then it will be added to array.
here is my code:
public class Trial02
{
public static void main( String[] args)
{
int[] bag = new int[100];
bag[0] = 2; //first element of prime array
int valid = 1;
int i;
boolean result = true;
String str = "";
//starting from 3 it checks if a number is prime until array is full
for( i=3; valid<bag.length; i++)
{
//it checks if previous primes in array are divisible by current number until coming to current number
for(int k=0; k<valid; k++)
{
if( i % bag[k] == 0)
result = false;
}
if( result == true) //if it is prime it is added to array
{
bag[valid] = i;
valid ++;
}
}
//printing results
for(int m=0; m < bag.length; m++)
str = str + bag[m] + " ";
System.out.println("zaa xd");
System.out.println(str);
}
}
but it don't give any output, just a blank. I couldn't find where my mistake is.
Thanks in advance.
You're never actually checking if a number is prime or not (result isn't being set anywhere useful)
It looks like you need to reset result = true; inside the first for loop. Your code as posted sets result = false and then never changes it.
The most obvious error is that your boolean result = true; is outside the loop: once set to false, it never gets set back to true. You do not see any output because your program never stops.
As a side note, you do not need to check all primes all the way to the last one you've discovered: you can stop once you reach the square root of the candidate prime, i.e. i*i > bag[k]. You are not going to notice any effect when your limit is 100, but if you try 100000, it would help a lot more.
Your logic for determining the first 100 prime numbers is incorrect. And number of logical errors are present as indicated by others. I have re-written your code but not tested. I guess it will work:
public class Trial02
{
public static void main( String[] args)
{
int[] bag = new int[100];
bag[0] = 2; //first element of prime array
int valid = 1;
int i;
boolean isPrime = true;
String str = "";
//starting from 3 it checks if a number is prime until array is full
for( i=3; valid<bag.length; i++)
{
isPrime = true;
for (int k = 2; k < i; k++)
{
if (i % k == 0)
{
isPrime = false;
break;
}
}
if (isPrime == true)
{
bag[valid++] = i;
}
}
//printing results
for(i=0; i < bag.length; i++)
str = str + bag[i] + " ";
System.out.println("zaa xd");
System.out.println(str);
}
}
You have a number of logical mistakes in your code.
First you have a for loop that has a finalization case unrelated to its indexer. While this is valid, it makes the code harder to understand.
More importantly, result is only ever set to false, not true, so thus the loop will run forever, as valid is never changed.

Categories