Prime numbers in array - java

I need to write a function that recieve from the user a number(n), and the function return an array with all the prime numbers until the user number(n).
I know how to write the function that check if number is prime, but i dont know how to enter the numbers to an array.. for example if the user entered 53, it will return [2 ,3 ,5 ,7 ,11 ,13 ,17 ,19 ,23 ,29 ,31 ,37 ,41 ,43 ,47 ,53].
I forgot to tell that the language is java.. my bad!

Here is the code
private ArrayList getPrimeNumbers(int number)
{
ArrayList primeNumbers = new ArrayList();
for (int i = 0; i <= number; i++)
{
if(isPrime(i))
{
primeNumbers.add(i);
}
}
return primeNumbers;
}
private boolean isPrime(int n)
{
for(int i=2;i<n;i++)
{
if(n%i==0)
return false;
}
return true;
}

Usually, you can't change array length, so you should use the appropriate
collection where you can add items; that is List<> in C#, ArrayList<> in Java etc.
Technically, you can implement separate IsPrime method and then check the integers in 2..max range, but here it can just be inlined.
Possible code in C#
public static int[] GetPrimes(int max) {
if (max <= 1)
return new int[0];
else if (max == 2) // <- let's process the only even prime (2) separately
return new int[] { 2 };
List<int> primes = new List<int>() { 2, 3 };
// Sieve through odd numbers:
for (int i = 5; i <= max; i += 2) {
int sqrt = (int) Math.Sqrt(i + 1);
Boolean isPrime = true;
// There's no need to check if (i % primes[0] == 0):
// primes[0] == 2, and loop is for odd numbers - 5, 7, 9,...
for (int j = 1; primes[j] <= sqrt; ++j)
if ((i % primes[j]) == 0) {
isPrime = false;
break;
}
if (isPrime)
primes.Add(i);
}
return primes.ToArray();
}
// ....
// Test will return the string
// "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53"
String result = String.Join(", ", GetPrimes(53).Select(x => x.ToString()));

Here is one way to do it (you did not specify language, so I'm using Python):
def GetPrimes(n):
array = []
for i in range(2,n+1):
if IsPrime(i):
array.append(i)
return array
def IsPrime(n):
for i in range(2,n/2+1):
if n % i == 0:
return False
return True
print GetPrimes(53)

The following code will work, Give it a try
package CoreJava;
public class prime {
public static void main(String[] args) {
int a [] ={1, 2, 3, 7, 23,7,10};
int flag=0;
for(int i=0;i<a.length-1;i++)
{
if((a[i]!=0) &&(a[i]!=1))
{
for(int j=2;j<a[i];j++)
{
if(a[i]%j==0)
{
flag=1;
break;
}
}
if(flag==0)
{
System.out.println(a[i]);
}
}
}
}
}

Related

Testing array issue

I am stuck on an issue that I cannot seem to resolve. I cannot seem to to test my code correctly. My code is as follows
public static int sum13( int[] nums) {
int sum = 0;
for(int i = 0; i <= nums.length - 1; i++){
if( nums[i] != 13){
sum += nums[i];
if(i > 0 && nums[i-1] == 13)
sum -= nums[i];
}
}
return sum;
}
public static void main(String[] args) {
}
If I try to put System.out.println(sum13([1,2,2,1]) I am met with several errors relating to the [] as well as the ,. I cannot figure out, what it is that I've done wrong.
Return the sum of the numbers in the array, returning 0 for an empty array. Except the number 13 is very unlucky, so it does not count and numbers that come immediately after a 13, also do not count. sum13([1, 2, 2, 1]) →6
sum13([1, 1]) →2
I decided to add flag to know when the previous value was 13. In that way, you don't have to deal with edge cases.
public static int sum13(int[] nums) {
int sum = 0;
boolean was13 = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 13) {
was13 = true;
} else {
if(!was13)
sum += nums[i];
was13 = false;
}
}
return sum;
}
A possible solution with some test cases:
public static int sum13(int[] numbers)
{
int sum = 0;
int prev = 0;
for (var number : numbers)
{
if (number != 13 && prev != 13)
{
sum += number;
}
prev = number;
}
return sum;
}
public static void main(String[] args)
{
System.out.println(sum13(new int[]{}));
System.out.println(sum13(new int[]{1, 2, 3, 4, 5}));
System.out.println(sum13(new int[]{13, 1, 13, 13, 2, 3, 4, 5}));
}

isSorted? Check array if is sorted in ascending or descending order in Java

can someone help me check my codes if are right or help me know if there is any other is way to solve this question I was trying to check if an array is in ascending or descending order then return 1 if not then return 0; at first I created some method for sorting array in increasing order and order and another method for decreasing and then I used those method to compare with the original array if it is sorted. I used the code below:
public class IsSorted {
public static void main(String[] args){
int[] list ={4,3,2,1};
System.out.println(isSorted(list));
}
public static int isSorted(int[] a){
if(a.length==0){
return 1;
}
if(a.length==1){
return 1;
}
int[] holdingArray=new int[a.length];
for (int i =0; i<a.length; i++){
holdingArray[i]=a[i];
}
int[] virtualIncreasedArray= new int[holdingArray.length];
int[] virtualDecreasedArray= new int[holdingArray.length];
sortIncrease(holdingArray);
for(int i=0; i<holdingArray.length;i++){
virtualIncreasedArray[i]=holdingArray[i];
}
sortDecrease(holdingArray);
for(int i=0; i<holdingArray.length;i++){
virtualDecreasedArray[i]=holdingArray[i];
}
//check if array is decreasing
for(int i=0; i<virtualDecreasedArray.length;i++){
if(virtualDecreasedArray[i]!=a[i]&&virtualIncreasedArray[i]!=a[i]){
return 0;
}
}
//check if array is increasing
return 1;
}
static void sortIncrease(int[] a){
for(int unsorted=a.length-1; unsorted>0; unsorted--){
for(int i=0; i<unsorted;i++){
if(a[i]>a[i+1]){
swap(a,i,i+1);
}
}
}
}
static void sortDecrease(int[] a){
for(int unsorted=a.length-1; unsorted>0; unsorted--){
for(int i=0; i<unsorted; i++){
if(a[i]<a[i+1]){
swap(a,i,i+1);
}
}
}
}
static void swap(int[] a, int i, int j){
if(i==j){
return;
}
int temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
For an accurate verification, the following should be done as there are important side cases to consider.
Checking if any list starts out with some number of equal values.
Determine the starting index where the values first differ.
If all the values are equal, return true immediately.
Note that in the worst case when all the values are equal, the entire array needs to be checked (sans the last value since then it could be either ascending or descending).
int[] sortedAscending = { 1, 1, 3, 4, 7, 10, 11, 15, 15 };
int[] sortedDescending = { 22, 22, 12, 8, 8, 8, 5, 2, 1 };
int[] sortedBoth = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int[] unsorted = { 2, 1, 2, 19, 19, 2, 4 };
System.out.println(isSorted(sortedAscending));
System.out.println(isSorted(sortedDescending));
System.out.println(isSorted(sortedBoth));
System.out.println(isSorted(unsorted));
Prints
true
true
true
false
The check method.
public static boolean isSorted(int[] arr) {
int start = 0;
// if the lists start with equal values, need to
// determine a starting point.
while (arr[start] == arr[start+1]
&& start++ < arr.length - 2);
if (start >= arr.length - 2) {
// all but the last the same value, its sorted
return true;
}
boolean asc = arr[start] < arr[start + 1];
for (int i = start; i < arr.length - 1; i++) {
if (asc) {
//check ascending
if (arr[i] > arr[i + 1]) {
return false;
}
// check descending
} else if (arr[i] < arr[i + 1]) {
return false;
}
}
return true;
}
Since you asked for another way to do this, here is a different approach.
What you could do is:
Determine whether the array is (supposedly) sorted in ascending or descending order based on the first 2 elements (if these exist)
Consider equal values when determining the supposed sorting (thanks for pointing that out #WJS)
Then, check the rest of the array for the correct order, based on what was determined
Updated Example:
public static void main(String[] args) {
int[] sortedAsc = { 1, 2, 3, 4, 5 };
int[] sortedDesc = { 5, 4, 2, 1 };
int[] unsortedArray = { 1, 8, 2, 4 };
int[] allEqual = { 3, 3, 3, 3, 3 };
int[] firstEqual = { 2, 2, 3, 2 };
System.out.println(isSorted(sortedAsc));
System.out.println(isSorted(sortedDesc));
System.out.println(isSorted(unsortedArray));
System.out.println(isSorted(allEqual));
System.out.println(isSorted(firstEqual));
}
public static boolean isSorted(int[] arr) {
boolean isAscending = false;
if (arr.length < 2) { // if the array has less than 2 elements, must be sorted
return true;
}
if (arr[0] < arr[1]) { // do we think this array is sorted ascending?
isAscending = true;
} else {
int index = 0;
while (arr[index] == arr[index + 1] && index++ < arr.length - 2) {
// keep checking for sorting if array consists of equal values
if (index >= arr.length - 2) {
return true; // whole array consists of equal values
}
}
// now that equal values were skipped, check for sorting again
isAscending = arr[index] < arr[index + 1];
}
// check all elements of the array
for (int i = 0; i < arr.length - 1; i++) {
if (isAscending) {
if (arr[i] > arr[i + 1]) {
return false;
}
} else {
if (arr[i] < arr[i + 1]) {
return false;
}
}
}
return true;
}
Output:
true
true
false
true
false
Sidenotes for your code:
Instead of returning an int (0, 1), your isSorted() method should definitely return boolean.
There is no point in the holdingArray.

How to iterate over array of integers to find a sequence based on an O(N) solution?

I saw following question and tried to find an answer for that.
Question: Given a sequence of positive integers A and an integer T, return whether there is a *continuous sequence* of A that sums up to exactly T
Example
[23, 5, 4, 7, 2, 11], 20. Return True because 7 + 2 + 11 = 20
[1, 3, 5, 23, 2], 8. Return True because 3 + 5 = 8
[1, 3, 5, 23, 2], 7 Return False because no sequence in this array adds up to 7
Note: We are looking for an O(N) solution. There is an obvious O(N^2) solution which is a good starting point but is not the final solution we are looking for.
My answer to above question is:
public class Tester {
public static void main(String[] args) {
int[] myArray = {23, 5, 4, 7, 2, 11};
System.out.println(isValid(myArray, 20));
}
public static boolean isValid(int[] array, int sum) {
int pointer = 0;
int temp = 0;
while (pointer < array.length)
{
for (int i = pointer; i < array.length; i++)
{
if (array[i] > sum)
break;
temp += array[i];
if (temp == sum)
return true;
else if (temp > sum)
break;
// otherwise continue
}
temp = 0;
pointer++;
}
return false;
}
}
I think my answer is O(N^2) which is not acceptable based on Question. Is there a solution based on O(N)?
You only need to loop once actually which is O(N).
Start adding from index 0 and once you exceed the sum start removing from the beginning of the array. if temp falls below sum continue looping.
public static boolean isValid(int[] array, int sum) {
int init = 0,temp = 0;
for (int i = 0; i < array.length; i++) {
temp += array[i];
while (temp > sum) {
temp -= array[init];
init++;
}
if (temp == sum)
return true;
}
return false;
}
What you should do is to have two indices (start and stop) then you increase stop until the sum is the required (and return true) or above. Then you increase start until the sum is the required (and return true or below. Then you repeat this until you reach the end of the array. You can update the sum incrementally (add the element when you increase stop and subtract when you increase start). This ought to be O(N).
Here's an example:
public class t {
public static void main(String[] args) {
int[] myArray = {23, 5, 4, 7, 2, 11};
System.out.println(isValid(myArray, 20));
}
public static boolean isValid(int[] array, int sum) {
int start = 0;
int stop = 0;
int tsum = 0;
while( true )
{
if( tsum < sum )
{
if( stop >= array.length )
break;
tsum += array[stop];
stop++;
}
else if( tsum > sum )
{
tsum -= array[start];
start++;
}
else if( tsum == sum )
return true;
// System.out.println(start + " -- " + stop + " => " + tsum);
}
return false;
}
}

remove and print prime numbers in an array

I have an assignment due for class and the objective is to take an Array and run it through a method that will print the array out in reverse order, then run it through a second method to test if the number is prime then print the still reversed order array out without the prime numbers. I can get the reverse the order part fine, I am running into trouble with the prime numbers part:
public class Driver {
public static void main(String[] args) {
// CTORs
int[] MyArray = { 10, 8, 7, 14, 22, 11 };
int[] myArray2 = new int[7];
// METHOD CALLING
MyArray = reverseOrder(6, MyArray);
MyArray = primeCheck(MyArray, 6);
for (int i = 0; i < myArray2.length; i++)
System.out.println(myArray2[i] + " ");
}// MAIN
/*--------------------ARRAY PRIME TEST---------------------*/
private static int[] primeCheck(int[] myArray, int num) {
//prime
boolean prime = true;
int[] myArray2 = new int[10];
//test all components of an array
for (int i = num + 1 ; i >= 0; i++) {
if (num % i > 0) {
prime = false;
System.arraycopy(myArray, 0, myArray2, 0, 4);
return myArray2;
}
}
return myArray2;
}// ISPRIME REMOVE
}// CLOSE CLASS
my output is as follows:
11 22 14 7 8 10 0
0
0
0
0
0
I feel really rusty because this is the first assignment back after a long break, so any guidance or help would be greatly appreciated.
myArray2 is defined and never filled with values. So every element is 0.
I think
for (int i = 0; i < myArray2.length; i++)
must be
for (int i = 0; i < myArray.length; i++)
There's definitely something wrong about for (int i = num + 1 ; i >= 0; i++). Below is one way to achieve the objective.
public static void main(String[] args) {
int[] arr = { 10, 8, 7, 14, 22, 11 };
for(int i = 0; i < arr.length; i++) {
if(!isPrime(arr[i])) {
System.out.print(arr[i] + " ");
}
}
}
public static boolean isPrime(int num) {
if(num < 2) return false;
if(num == 2) return true;
int remainder, divisor;
divisor = num - 1;
do {
try {
remainder = num % divisor;
} catch (ArithmeticException e) {
return false;
}
if(remainder == 0) return false;
divisor--;
} while (divisor > 1);
return true;
}

Array even & odd sorting

I have an array where I have some numbers. Now I want to sort even numbers in a separate array and odd numbers in a separate. Is there any API to do that? I tried like this
int[] array_sort={5,12,3,21,8,7,19,102,201};
int [] even_sort;
int i;
for(i=0;i<8;i++)
{
if(array_sort[i]%2==0)
{
even_sort=Arrays.sort(array_sort[i]);//error in sort
System.out.println(even_sort);
}
}
Plain and simple.
int[] array_sort = {5, 12, 3, 21, 8, 7, 19, 102, 201 };
List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
for (int i : array_sort) {
if ((i & 1) == 1) {
odd.add(i);
} else {
even.add(i);
}
}
Collections.sort(odd);
Collections.sort(even);
System.out.println("Odd:" + odd);
System.out.println("Even:" + even);
Your question as stated doesn't make sense, and neither does the code. So I'm guessing that you want to separate the elements of an array into two arrays, one containing odds and the other evens. If so, do it like this:
int[] input = {5, 12, 3, 21, 8, 7, 19, 102, 201};
List<Integer> evens = new ArrayList<Integer>();
List<Integer> odds = new ArrayList<Integer>();
for (int i : input) {
if (i % 2 == 0) {
evens.add(i);
} else {
odds.add(i);
}
}
You can then convert a list of Integer to a sorted array if int as follows:
List<Integer> list ...
int[] array = new int[list.size()];
for (int i = 0; i < array.length; i++) {
array[i] = list.get(i);
}
Arrays.sort(array);
or if a sorted List<Integer> is what you need, just do this:
Collections.sort(list);
It's simple to do this using Guava.
Use Ints.asList to create a List<Integer> live view of an int[]
Define a Function<Integer,Boolean> isOdd
Use Ordering that compares onResultOf(isOdd), naturally (i.e. false first, then true)
If necessary, compound that with an Ordering.natural()
Here's the snippet:
int[] nums = {5,12,3,21,8,7,19,102,201};
Function<Integer,Boolean> isOdd = new Function<Integer,Boolean>() {
#Override
public Boolean apply(Integer i) {
return (i & 1) == 1;
}
};
Collections.sort(
Ints.asList(nums),
Ordering.natural().onResultOf(isOdd)
.compound(Ordering.natural())
);
System.out.println(Arrays.toString(nums));
// [8, 12, 102, 3, 5, 7, 19, 21, 201]
Note that all the even numbers show up first, then all the odd numbers. Within each group, the numbers are sorted naturally.
External links
polygenelubricants.com - Writing more elegant comparison logic with Guava's Ordering
There are some things to know first :
You must initialize an array before using it. For example int[] even_sort = new int[3];
In java arrays have a static size. That means that you won't be able to add as many elements as you want. You have to choose a size before. You should take a look at Java Collections, it's a good way to get rid of this "rule" the java way.
The Arrays.sort() method apply on arrays only. Here array_sort[i] is an int
Arrays.sort() sorts an array but doesn't return anything.
If you really want to use arrays (but you shouldn't) you can do something like this to resize one :
int[] even_sort = new int[3]{1, 2, 3};
int[] temp = new int[4];
System.arraycopy(even_sort, 0, temp, 0, even_sort.length);
even_sort = temp;
even_sort[3] = 4;
Another way would be creating an utility method which uses reflection to create the new array :
import java.lang.reflect.Array;
public Object resizeArray(Object originalArray, int newSize){
int originalSize = Array.getLength(originalArray);
Class arrayType = originalArray.getClass().getComponentType();
Object newArray = Array.newInstance(arrayType, newSize);
System.arraycopy(originalArray, 0, newArray, 0, Math.min(originalSize, newSize));
return newArray;
}
So if you still want to use array for some reasons (but you still shouldn't) here is a code to filter, resize and sort your array.
int[] arrayToFilterAndSort = {5, 12, 3, 21, 8, 7, 19, 102, 201};
int[] sortedEvens = new int[0];
for(int current : arrayToFilterAndSort){
if((current & 1) == 1){
sortedEvens = resizeArray(sortedEvens, sortedEvens.length + 1);
sortedEvens[sortedEvens.length - 1] = current;
}
}
Arrays.sort(sortedEvens);
Resources :
oracle.com - Arrays tutorial
oracle.com - Collections tutorial
javadoc - Arrays.sort()
package com.java.util.collection;
import java.util.Arrays;
/**
* Given n random numbers. Move all even numbers on left hand side and odd numbers on right hand side and
* then sort the even numbers in increasing order and odd numbers in decreasing order For example,
* i/p : 3 6 9 2 4 10 34 21 5
* o/p: 2 4 6 10 34 3 5 9 21
* #author vsinha
*
*/
public class EvenOddSorting {
public static void eventOddSort(int[] arr) {
int i =0;
int j =arr.length-1;
while(i<j) {
if(isEven(arr[i]) && isOdd(arr[j])) {
i++;
j--;
} else if(!isEven(arr[i]) && !isOdd(arr[j])) {
swap(i,j,arr);
} else if(isEven(arr[i])){
i++;
} else{
j--;
}
}
display(arr);
// even number sorting
Arrays.sort(arr,0,i);
Arrays.sort(arr,i,arr.length);
// odd number sorting
display(arr);
}
public static void display(int[] arr) {
System.out.println("\n");
for(int val:arr){
System.out.print(val +" ");
}
}
private static void swap(int pos1, int pos2, int[] arr) {
int temp = arr[pos1];
arr[pos1]= arr[pos2];
arr[pos2]= temp;
}
public static boolean isOdd(int i) {
return (i & 1) != 0;
}
public static boolean isEven(int i) {
return (i & 1) == 0;
}
public static void main(String[] args) {
int arr[]={3, 6, 9 ,2, 4, 10, 34, 21, 5};
eventOddSort(arr);
}
}
int arr[20] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "The Even no are : \n";
for (int i = 1; i <= 10; i++) // for start for only i....(even nos)
{
if (i % 2 == 0)
{
cout << i;
cout << " ";
}
}
cout << "\nThe Odd no are : \n";
for (int j = 1; j <= 10; j++) // for start for only j....(odd nos)
{
if (j % 2 != 0)
{
cout << j;
cout << " ";
}`enter code here`
}
package srikanth dukuntla;
public class ArrangingArray {
public static void main(String[] args) {
int j=0;
int []array={1,2,3,5,4,55,32,0};
System.out.println(array.length);
int n=array.length/2;
for (int i=0; i<array.length; i++){
if(array[i]%2!=0){
j=1;
int temp=array[array.length-j];
if(temp % 2!=0){
while((array[array.length-(j+1)]%2!=0) && (array.length-(j+1)>n)){
j++;
}
int temp2=array[array.length-(j+1)];
array[array.length-(j+1)] =array[i];
array[i]=temp2;
}else // inner if
{
array[array.length-j] =array[i];
array[i]=temp;
}
}else //main if
{
//nothing needed
}
}
for(int k=0;k<array.length;k++) {
System.out.print(" "+ array[k]);
}
}
}
List < Integer > odd = new ArrayList < Integer > ();
List < Integer > even = new ArrayList < Integer > ();
int a [] = {0,2,3,98,1,6546,45323,1134564};
int i;
for (i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
even.add(a[i]);
} else {
odd.add(a[i]);
}
}
System.out.print("Even: " + even + "\n");
System.out.print("Uneven: " + odd + "\n");
}
}

Categories

Resources