delete prime numbers from an array-java - java

How can I do in order to delete prime numbers not including 0 and 1 and I want to find just prime numbers excluding 0 and 1?Now if I have{0,1,3,5,8}----> after compiling it will find 0 and 1 as prime numbers ."Prime Number Found=0 Prime Number Found=1 Prime Number Found=3 Prime Number Found=5" Here's my program:
Thank you for your help.
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int i,j,size;
boolean status;
System.out.print("Enter size of array=");
size=s.nextInt();
int arr[]=new int[size];
int tmp[]=new int[size];
System.out.println("Enter Elements in array...");
for(i=0;i<size;i++)
{
arr[i]=s.nextInt();
}
for( i=0;i<size;i++)
{
status=true;
for(j=2;j<arr[i]-1;j++)
{
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
}
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
}
}

Your code was full of problems, but in the code below I did fix the following major problems:
you were not handling the base case of 0 and 1 being not prime correctly
your loop for scanning for possible whole number divisors had the wrong bounds
you were not writing the found prime numbers correctly to the output array which you were printing at the end of the main() method.
Have a look at the code below for a sample of what you probably intended to do.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean status;
System.out.print("Enter size of array=");
int size = s.nextInt();
int arr[] = new int[size];
int tmp[] = new int[size];
System.out.println("Enter Elements in array...");
int primerCounter = 0;
for (int i=0; i < size; i++) {
arr[i] = s.nextInt();
}
for (int i=0; i < size; i++) {
status = true;
if (arr[i] == 0 || arr[i] == 1) {
status = false;
}
else {
for (int j=2; j <= arr[i]-1; j++) {
if (arr[i] % j ==0) {
status = false;
break;
}
}
}
if (status == true) {
tmp[primerCounter++] = arr[i];
System.out.println("Prime Number Found="+arr[i]);
}
}
System.out.println("New Array....");
for (int i=0; i < primerCounter; i++) {
System.out.println(tmp[i]);
}
}
For an input of the numbers from 0 to 20 inclusive, I got the following output:
{2, 3, 5, 7, 11, 13, 17, 19}

Your question is not very clear, but I am assuming your problem is that the code you posted considers 0 and 1 as prime numbers, and you don't want that. If that's the case. the error is that the check
(arr[i]==0)||arr[i]==1)
is within the for loop
for(j=2;j<arr[i]-1;j++)
In fact, when arr[i] is equal to 0 or 1, the condition
j<arr[i]-1
will evaluate to false immediately, because j=2 and arr[i]-1 evaluates to either -1 or 0. As a consequence, the code
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
will never be executed, and in the following loop
status==true
will evaluate to true.
One solution is to remove the check
arr[i]==0)||arr[i]==1
from where it is now and put it in the same if as the one whose condition is
status==true
after changing == with !=.
In a nutshell,
if(arr[i]%j==0||(arr[i]==0)||arr[i]==1)
{
status=false;
tmp[i]=arr[i];
break;
}
should become
if(arr[i]%j==0)
{
status=false;
tmp[i]=arr[i];
break;
}
and
if(status==true)
{
System.out.println("Prime Number Found="+arr[i]);
}
should become
if(status==true || arr[i]!=0 || arr[i]!=1)
{
System.out.println("Prime Number Found="+arr[i]);
}
There's another mistake in the code you posted: you use the same index i to iterate over arr and to select the elements of tmp to whom assign values. As not every element of arr is prime and will not therefore be copied to tmp, this results in an array tmp with some "holes", i.e, unassigned elements. You should keep a different index k initialized to 0 to access the elements of tmp and increment it manually:
tmp[k]=arr[i];
k++;
instead of
tmp[i]=arr[i];
Also, when you eventually iterate over tmp bear in mind that its size won't be the same as arr, but smaller (for the reason I have just explained). Thus,
for(i=0;i<size;i++)
{
System.out.println(tmp[i]);
}
should be replaced with
for(i=0; i < actual-size-of-tmp; i++)
{
System.out.println(tmp[i]);
}

Related

Trying to find a a perfect number within an upper limit in java without creating a method

I'm just trying to print the perfect numbers within a certain upper limit, but I get other numbers that show up, that aren't perfect numbers. I'm not trying to use a method, rather than just everything in the main loop. I need some help.
public static void main(String arg[]) {
int upper;
int sum = 0;
int i;
System.out.println("Enter upper limit");
Scanner stnd = new Scanner(System.in);
upper = stnd.nextInt();
for(int n = 1; n < upper; n++) {
i = 1;
sum = 0;
while (i <= n/2) {
if (n%i == 0) {
sum = sum + i;
}
i++;
if(sum == n) {
System.out.println(n+" is a perfect number");
break;
} else {
}
}
}
}
You've got a while loop in your code that adds up the factors of the number. The problem is that you're checking the sum, when the while loop isn't yet finished. In the case of 24, you've added up
1 + 2 + 3 + 4 + 6 + 8
which is 24, but your loop hasn't got to 12 yet.
You need to move
if(sum == n) {
System.out.println(n+" is a perfect number");
}
to after the while loop, rather than having it inside the loop.

Java number sequence loop

So hi i'm getting infinite loop problem i don't know whats wrong with my code i'm trying to make a number sequence format is at the bottom i think the problems are in my condition?
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
while(n!=0) { //is this right?
for ( int i = 0; i<=n; i++) {
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Outputs i'm trying to get
Enter how many numbers to display : 5
1 3 6 8 11
2.
Enter how many numbers to display : 16
1 3 6 8 11 13 16 18 21 23 26 28 31 33 36 38 //but im getting infinite loops
// the sequence pattern is +2 then +3
The problem is here: while(n!=0) and here: for ( int i = 0; i<=n; i++). For the while loop, will keep on going until n is equal to 0. For the for loop, this will most likely keep on going for ever.
Your code has two problems:
If you provide a non negative value, this will keep on going for ever (since you are always only incrementing n).
Even if you do supply a negative number, n would n need to become exactly 0 to stop.
Depending on what you need to do, you will need to change the condition. Judging by the output, n would need to be positive and thus you would need to stipulate some upper range for n in which the while loop would stop.
EDIT: You only need to have 1 loop to do what you are after. Also, n denotes the amount of elements, thus it needs to stay fixed throughout the execution of the program. In your case, you where increasing it all the time.
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int count = 0;
int i = 1;
while (count < n) { //is this right?
if (count % 2 == 0) {
System.out.print(i + " ");
i += 2;
} else {
System.out.print(i + " ");
i += 3;
}
count++;
}
Two problems:
int stop = n; // declare one local var to stop the for loop
if (n != 0) { //switch to if condition
for (int i = 0; i <= stop; i++) {
//loop's exit condition wasn't met because 'n' was also being incremented
if (i % 2 == 0) {
n += 2;
System.out.print(n+" ");
} else {
n += 3;
System.out.print(n+" ");
}
}
}
Use 'if' condition in place of 'while' loop
You have to replace your while-loop with an if-condition like so:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int stop = n;
if(n!=0) { //if statement checks if n!=0
for ( int i = 0; i<=stop; i++) {
//stop replaces n because n is incremented in your for-loop
if(i%2==0) {
n += 2;
System.out.print(n);
} else {
n += 3;
System.out.print(n);
}
}
}
}
}
Based on your answers I found a solution that works:
int n;
System.out.print("Enter how many numbers to display");
n = x.nextInt();
int k = -2; // so that it starts with 1 when i add +3
int stop = n-1;
if(n!=0) {
for ( int i = 0; i<=stop; i++) {
if(i%2==0) {
k += 3;
System.out.print(k+" ");
} else {
k += 2;
System.out.print(k+" ");
}
}
}

Ascending order and Descending Java

Hi here's my problem i cant seem to print my outputs correctly i guess i'm having a logical error in my code, it doesn't print when i put an ascending number then a descending. i'm kind of new to programming too.
Code:
import java.util.Scanner;
public class tester {
public static void main(String[] args) {
int n, i, k, j;
int asc = 0,
Scanner x = new Scanner(System.in);
do {
System.out.print("How many numbers to process : ");
k = x.nextInt();
if(k<=1) {
System.out.println("Enter a number greater than 1");
}
} while(k<=1);
System.out.printf("Please enter %d numbers: ",k);
n = x.nextInt();
for(i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
}
}
Here are the outputs
Example outputs (what i'm trying to get)
How many numbers to process : 4
Please enter 4 numbers : 1 2 3 4
Growing up.
How many numbers to process : 4
Please enter 4 numbers : 4 3 2 1
Not Growing up.
This is my problem :
How many numbers to process : 4
Please enter 4 numbers : 1 2 1 3
Growing up. // it should be not growing up.
There is no need to iterate through all numbers. You can just check if the previous number is lower (if growing). If not, print and return. Check my example code.
Replace
n = x.nextInt();
for (i=0; i<n-1; i++) {
j = x.nextInt();
if( j < n) {
asc++; // is this right?
} else {
asc--;
}
}
if (asc==k) {
System.out.print("Not Growing Up.");
}
if (asc!=k) {
System.out.print("Growing Up.");
}
With
int prev = x.nextInt();
for (i=0; i<k-1; i++) {
j = x.nextInt();
if (j < prev) { System.out.print("Not Growing Up."); return; }
prev = j;
}
System.out.print("Growing Up.");
String numbers = "1 2 3 4"; // Let's take this input for example
int temp = 0; // This use to compare previous integer
boolean isAsc = false; // This store whether the digits is growing up or not
StringTokenizer st = new StringTokenizer(numbers); // Declare StringTokenizer
while (st.hasMoreTokens()) {
int next = Integer.parseInt(st.nextToken()); // Put the first integer in next (1)
if(next > temp){ // if (1) > 0
temp = next; // Assign 1 to temp, next time digit 2 will compare with digit 1
isAsc = true; // Assign the ascending to true
} else
isAsc = false;
}
if(isAsc)
System.out.print("Growing up.");
else
System.out.print("Not growing up.");
}
Your can store the user input as a string like the variable numbers I've declared and break them into each token for compare purpose.
import java.lang.reflect.Array;
import java.util.*;
public class A1 {
public static void main(String[] args) {
int a[]={2,5,0,1};
Arrays.sort(a);
int b= a.length;
for(int i=0;i<a.length;i++)
{
System.out.println(+a[i]+"\t"+a[b-1]);
b--;
}
}
}

Can find all the prime numbers but doesn't include "2"?

It now can find all the prime numbers in the input range, but it can't find number 2, the smallest prime number.
for(int number=2;number<range;number++){
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
if(number%testDivide!=0) {
System.out.println(number);
}
break;
}
For range 10 it prints:
5
7
9
but no 2.
The reason your code is not producing correct results (missing 2 and 3; including 9) is that your primality test logic is backwards. A number is prime if the inner loop completes without finding any even divisors; instead you are printing the number if you find any non-divisor.
Try this instead:
for( int number = 2; number < range; number++) {
boolean divisible = false;
int limit = (int) Math.sqrt(number);
for (int testDivide = 2; !divisible && testDivide <= limit; testDivide++) {
divisible = number % testDivide == 0;
}
if (!divisible) {
System.out.println(number);
}
}
Note that a much more efficient way to generate all primes in a range is the Sieve of Eratosthenes.
check the code here:
package core;
public class Test2 {
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Note that one of the best ways to generate a list of prime numbers is the "Sieve of Erwhatshisface":
Create a list of consecutive integers starting with 2, up to the max number you'd like to search. Take the first non-zero number in the list (2) and repeatedly step 2 from that location, zeroing out every 2nd list element.
Next take the second non-zero number (3) and repeatedly step 3 from that location, zeroing. Continue with each non-zero value in the list, until you've processed all of them (or at least halfway through, at which point you'll be stepping beyond the end of the list).
The non-zero numbers remaining are all primes.
Reposting code here as not fit in comments:
public static void main(String[] args) {
int cnt = 0;
for (int i = 2;; i++) {
if(i==2){
System.out.println(i);
continue;
}
if (Priem(i)) {
cnt++;
System.out.println(i);
if (cnt == 200)
break;
}
}
}
public static boolean Priem(int n) {
for (int i = 2; i <Math.sqrt(n)+1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
I think you have your for loop a little mixed up.
for(int testDivide=2;testDivide<Math.sqrt(number);testDivide++){
}
Not sure why you are stopping when testDivide is equal to sqrt(number), you should stop when testDivide is greater than.
Also inside your inner for loop isn't correct either:
if(number%testDivide!=0) {
System.out.println(number);
}
break;
Basically all this will do is check to see of the number is divisible by 2 and then break. You only need to break when you find a number which cleanly divides (number%testDivide==0). Maybe keep a boolean which you set to true when you break and only print after the inner for loop finishes if that boolean is false.
Something along the lines:
for (int number=2; number<range; number++){
boolean found = false;
int limit = (int)Math.sqrt(number);
for (int testDivide=2; testDivide<=limit; testDivide++){
if(number%testDivide==0) {
found = true;
break;
}
}
if (!found) System.out.println(number);
}
In your code when number is 2, sqrt(2) is 1.41 and control doesn't go into the loop. I didn't get the logic behind iterating upto sqrt(number). Try this code
public class Test {
public static void main(String[] args) {
int range = 500; //I assume
for (int i = 2; i< range; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
public static boolean isPrime(int number) {
for (int i = 2; i <= number/2; i++) {
if (number % i == 0) {
return false;
}
if(i % 2 == 1) {
i++; //If not divided by 2 then
// need not to check for any even number
// Essentially incrementing i twice hereafter
}
}
return true;
}
}

Wrong Answer for Project Euler 50

I am attempting Problem 50 of project Euler.
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive
primes that adds to a prime below one-hundred. The longest sum of
consecutive primes below one-thousand that adds to a prime, contains
21 terms, and is equal to 953. Which prime, below one-million, can be
written as the sum of the most consecutive primes?
Here is my code:
public class consPrime
{
static int checker(int ar[],int num,int index) //returns no.of consecutive
{ //primes for the given num
while(true)
{
int temp=num;
for(int i=index;i>=0;i--)
{
temp=temp-ar[i];
if(temp==0)
{
return (index-i+1);
}
}
index--;
if(index==0)
return 0;
}
}
public static void main(String args[])
{
int n=100000;
int ar[]=new int[n];
int total=0;int flag;
for(int i=2;i<1000000;i++) //Generates an array of primes below 1 million
{
flag=1;
for(int j=2;j<=Math.sqrt(i);j++)
{
if(i%j==0)
{
flag=0;
break;
}
}
if(flag==1)
{
ar[total]=i;
total++;
}
}
int m=0;
int Big=0;
for(int i=total;i>=0;i--) //Prints the current answer with no.of prime
{
m=checker(ar,ar[i],i-1);
if(Big<=m)
{Big=m;
System.out.println(ar[i]+" "+Big);
}
}
}
}
Basically it just creates a vector of all primes up to 1000000 and then loops through them finding the right answer. The answer is 997651 and the count is supposed to be 543 but my program outputs 990707 and 75175 respectively. What might be wrong?
Several big problems:
Some minor problem first: learn to proper indent your code, learn to use proper naming convention. In Java, variable names uses camelCasing while type name uses PascalCasing.
Lots of problems in your logics: you loop thru the prime number array, until you hit zero or until looped thru all numbers in the array. However, please be awared that, there is underflow/overflow for integer. It is possible that the "temp" keeps on deducts and become negative and become positive and so-on-and-so-forth and hit zero. However that's not the correct answer
You only tried to find the consecutive numbers that ends at index - 1. For example, to check for prime number at index 10, you are finding consecutive primes from index 9 backwards. However consecutive prime sum up to your target number rarely (in fact almost never, except for 5) contains the "previous" prime number. The whole logic is simply wrong.
Not to mention the incorrect parameters you passed for checker, which is mentioned by comment of user #pm-77-1
Here is another approach that takes 43 ms.
It is based on the following approach:
1) The primes <= 1000000 are generated using a sieve
2) It iterates in O(n2) through all numbers and it counts the consecutive primes. The first loop changes the first element of the sequence, the second one takes the elements starting from that position and adds them to a sum. If the sum is prime and it consists of the biggest number of primes, than it is kept in a variable.
import java.util.ArrayList;
import java.util.List;
public class P50 {
private final static int N = 1_000_000;
public static void main(String[] args) {
boolean primes[] = generatePrimes(N);
List<Integer> primeIntegers = new ArrayList<Integer>();
for (int i = 0; i < primes.length; i++) {
if (primes[i]) {
primeIntegers.add(i);
}
}
int count = 0;
int sum = 0;
int finalSum = 0;
int finalCount = 0;
int totalPrimes = primeIntegers.size();
for (int start = 0; start < totalPrimes; start++) {
sum = 0;
count = 0;
for (int current = start; current < totalPrimes; current++) {
int actual = primeIntegers.get(current);
sum += actual;
if ( sum >= N ) {
break;
}
if ( primes[sum] ) {
if ( count > finalCount ) {
finalCount = count;
finalSum = sum;
}
}
count++;
}
}
System.out.println(finalSum);
}
private static boolean[] generatePrimes(int n) {
boolean primes[] = new boolean[n];
for (int i = 0; i < n; i++) {
primes[i] = true;
}
primes[0] = false;
primes[1] = false;
// i = step
for (int i = 2; i * i < n; i++) {
if (primes[i]) {
for (int j = i * i; j < n; j += i) {
primes[j] = false;
}
}
}
return primes;
}
}

Categories

Resources