How to add and print prime numbers [closed] - java

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

Related

magic matchsticks problem geeks for geeks interview question [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 4 months ago.
Improve this question
I have given an interview in geeks for geeks where I was given a magic match sticks problem, I wasn't able to solve it in time. I solved it myself a day after, I wasn't able to find the solution as well on Stack Overflow, so here is the solution for you if you ever encounter that problem:
//magic match-stick problem
/*in this problem set we are given n number of match boxes,
* you need to add matches in a match that is
* the n number of matches in each box,
* but the catch is instead of adding the matches,
* you need to subtract the matches pair that you will be inserting in place
* of every new match stick until there is only last box left with final match stick score
* eg: 1st match box: 4match sticks: 1,2,3,4 match numbers
* 2nd time: 2 match sticks : (1-2), (3-4)=> 1, 1
* last time: (1-1) => 0
*
* I know I cannot explain the problem correctly in English, but I will be able to explain it to you in hindi v well
* also if you can understand the code, you will understand the question
* this took me one day to solve, many minor mistakes I did
* this is a geeks for geeks interview question
* question name magical matchsticks*/
public class practice{
public static void main(String args[]) {
int a[] = {1,2,3,4,5,6};
int num;
int count;
int n = a.length;
do
{
num=0;
count=0;
if(n==1)
{
System.out.println(a[0]+"last");
}
else if(n>1)
{
if(n%2==0)
{
n=n/2;
for(int i = 0; i<((n)) ; i++)
{
a[i] = a[num]-a[num+1];
if(a[i]<0)
{
a[i] = a[i]*(-1);
System.out.print(a[i]+" "+a[i + 1]);
}
System.out.println(" a ");
num = num + 2;
count++;
}
}
else if(n%2==1)
{
n = (n/2) +1;
for(int i = 0; i<(n); i++)
{
a[i] = a[num]-a[num+1];
if(a[i]<0)
{
a[i] = a[i]*(-1);
System.out.print(a[i]+" "+a[i + 1]);
}
System.out.println("b ");
num = num + 2;
count++;
}
}
}
System.out.println(n);
for(int j = 0; j<a.length;j++)
{
System.out.print(a[j]);
}
System.out.println(" ");
}while(n>1);
for(int k = 0; k<a.length;k++)
{
System.out.print(a[k]);
}
System.out.println(" ");
}
}
This problem will show you all the steps as the program goes on, you will need to make changes so it returns value from a separate class or function.
I'll be starting to provide solutions for competitive programming on this account.
this question is solved with answer given above.
also answer is provided on my github page: https://github.com/bruce-Wayn/java-qns/blob/6a9714225b4884aefbdad0441e721416c5843576/magic-match-sticks.java

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]

Runtime error - Java [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 was trying to find sum of even fibonacci number for a given set of N inputs(obtained from stdin)
This code is working well for some test cases but printing runtime error(No details given) for a test case.
Link for question: https://www.hackerrank.com/contests/projecteuler/challenges/euler002
code
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.util.*;
public class Solution {
public static Integer[] convert(int[] chars) {
Integer[] copy = new Integer[chars.length];
Arrays.fill(copy, 0);
for(int i = 0; i < copy.length; i++) {
copy[i] = Integer.valueOf(chars[i]);
}
return copy;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
int x, max;
int a[], sum[], fib[];
Scanner in = new Scanner(System.in);
x = in.nextInt();
a = new int[x];
sum = new int[x];
for(int i=0;i<x;i++)
{
a[i] = in.nextInt();
}
Integer[] b = convert(a);
max = Collections.max(Arrays.asList(b));
fib = new int[max];
if (max >1)
{
fib[0]=1;
fib[1]=1;
}
for(int i=2;i<max;i++)
{
fib[i] = fib[i-1]+fib[i-2];
}
for(int i =0;i<x;i++)
{
for(int j = 0;fib[j]<a[i];j++)
{
if(fib[j]%2 ==0)
sum[i] = sum[i] + fib[j];
}
}
for(int i=0;i<x;i++)
{
System.out.println(sum[i]);
}
}
}
Any help is appreciated.
I'll be more thankful if you can help me with an optimized version of the same.
Your code would throw ArrayIndexOutOfBoundsEception in some cases.
Let's consider what you are doing :
You are getting an input x from user
Then you create array a with x elements, input by user
Then you find the max element of a
You create an array fib of max elements, and calculate fib[i] for each i from 0 to max-1
Suppose the user inputs : 2 2 2
max would be 2, so fib would contain two elements : {1,1}
Now, the following loop will cause the exception :
for(int i =0;i<x;i++) // x is 3
{
for(int j = 0;fib[j]<a[i];j++) // both fib[0] and fib[1] < a[0]
// fib[2] would throw the exception
It is not clear what you are trying to do with this nested loop, but clearly it doesn't work.
i think the problem is that the Recursive call stack in java is so deep,so the java compiler will print RE. and to optimize this problem, frist,you can use the dp method to solve this problem。the dp method is to decrease the repeat count to the problem.
the link is http://zh.wikipedia.org/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92
hope to help you.

Find Prime Numbers based on user input [closed]

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

Problems with 3 way sort in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Hi I think there may be a problem with my 3 way sort algorithm in the following Java program, also any suggestion on optimizing or just a simpler it would be greatly appreciated. The objective of the sort is to have the minus numbers first then zeros and then positive numbers
class ThreeWaySort
{
public static void main(String[] args)
{
int location = 0;
int[] sArray = new int[50];
for (int a = 25; a<= -24; a--)
{
sArray[location] = a;
location++;
}
int i = 0; int j = 0; int k = 50;
while (j!=k)
{
if (sArray[j]==0)
{
j++;
}
else if (sArray[j]<0)
{
int t = sArray[i]; sArray[i] = sArray[j]; sArray[j] = t; // case (ii)
i++; j++;
}
else
{
k--;
int t= sArray[j]; sArray[j] = sArray[k]; sArray[k] = t;
}
}
for (int a = 0; a <= 49; a++)
{
if(sArray[a] >-1)
{
System.out.println();
System.out.println();
System.out.println();
}
if(sArray[a] > 0)
{
System.out.println();
System.out.println();
System.out.println();
}
System.out.print(sArray[a] + " ");
}
}
}
When i run the program as is it costantly print out a zero followed by three line instead of what I'm expecting to be, Numbers below zero in a line, followed by 3 blank lines then any zeros in the array, 3 blank lines, positive numbers in the array.
The loop that populates your array is incorrect:
for (int a = 25; a<= -24; a--)
The variable a starts at 25, which is not less than or equal to -24, so the loop never executes. You should use >=.

Categories