I want to find prime numbers given range using ArrayList. I have done following code.
import java.util.ArrayList;
import java.util.Iterator;
public class PrimeNumbers {
public static void main(String args) {
PrimeNumbers aaa=new PrimeNumbers();
Iterator<Integer> itr = aaa.printAllPrime(1, 10).iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
public ArrayList<Integer> printAllPrime(int k, int j) {
ArrayList<Integer> arrlist = new ArrayList<Integer>();
int count=0;
for(int i=k;i<=j;i++) {
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
//System.out.println(i+" "+count);
if(count == 2) {
arrlist.add(i);
}
}
return arrlist;
}
}
Expected:
[2, 3, 5, 7]
Current result:
[2, 4, 3, 5, 10]
I am fresh to java and please help me to find where I have done wrong here. Thank you.
Initialize count inside the first for loop, before the second one. Since count is never reset to 0 after each iteration, you are getting the wrong number.
public ArrayList<Integer> printAllPrime(int k, int j) {
ArrayList<Integer> arrlist = new ArrayList<Integer>();
// int count=0; <- here is incorrect
for(int i=k;i<=j;i++) {
int count = 0; // put it here
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
//System.out.println(i+" "+count);
if(count == 2) {
arrlist.add(i);
}
}
return arrlist;
}
That way, count will be for each individual number.
Hope this works for you!
for(int l=1;l<=i;l++) {
if(i%l == 0) {
count++;
}
}
In this part of your code, you literally check if, for example 4%2 == 0,
ofc it is, so 4 is also put in the array.
Also, your code can be significantly improved with some simple math.
So, if you test all the numbers up to the square root, you can rest
assured that the number is prime. For example, the square root of 23
is around 4.8, so you would test 23 to see if it can be divided by 2,
3 or 4. It cannot be, so 23 is prime.
Read more here
Related
I am trying to write a method that will take in the array int[] numbers and return the sum of all of the odd numbers in the array. I am not sure why it is not returning the correct value. Currently it returns "3" when it should be returning "9".
public static void main(String[] args) {
int[] numbers = { 2, 1, 5, 3, 0 };
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) { sumodds = +(array[i]);}
}
return sumodds;
}
sumodds =+ (array[i]) means "assign the value of array[i] to sumodds". The + and the () make no difference - it's semantically identical to sumodds = array[i]. Use this if you just want the last odd value in the array.
sumodds += array[i] means "increase the value of sumodds by array[i]. Use this if you're trying to sum the odd values in the array.
The reason of the error is in this piece of code...
if (array[i] % 2 != 0) {
sumodds = +(array[i]);
}
you are not summing or accumulating you are just assigning the value with a positive sign
at the end, your code is just returning the last odd value found in the array...
you have to do instead something like:
if (array[i] % 2 != 0) {
sumodds += array[i];
}
If you write too much code, you have more chance to go wrong, you should use java 8 Streams:
int sumOdd = Arrays.stream(array).filter(t -> t%2==1).sum();
System.out.println(sumOdd);
The problem was with your addition operator =+. It should be += if you want to add and assign the new value to the same variable. Please refer below working code.
public static void main(String[] args) {
int[] numbers = {2, 1, 5, 3, 0};
System.out.println(oddballsum(numbers));
}
public static int oddballsum(int array[]) {
int sumodds = 0;
for(int element : array) {
if(element % 2 != 0) {
sumodds += element;
}
}
return sumodds;
}
Suggest I have the following array :
{2,3,4,5,11,6} and I'd like to know if any items of the array contain a sum of the number x.
For example:
x=10, then the output would be {2,3,5} and {4,6}.
x=13, then the output would be {2,11},{3,4,6} and {2,5,6}
What would be an optimal algorithm to solve this problem?
I have thought of solving this using the possible permutations of the array, and check whether the sum of the beginning of each permutation equals to the X, but it doesn't seem to solve it.
Thanks!
My two cents solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, 3, 4, 5, 11, 6);
Collections.sort(list);
Integer sum = 0;
Integer max = 13;
for (int i=0; i<list.size(); i++) {
sumNext(list, i, sum,max, new ArrayList<Integer>());
}
}
private static void sumNext(List<Integer> list, int pos, Integer currentSum, Integer max,
List<Integer> currentElement) {
int nextSum = currentSum + list.get(pos);
if (nextSum > max) {
return;
}
currentElement.add(list.get(pos));
if (nextSum == max) {
for (Integer i : currentElement) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
} else if (nextSum < max && list.get(pos) < max - currentSum) {
// as array is sorted if current element is higher than the diff
// between currentSum and max there is no need to try with next
// element
for (int i=pos+1; i<list.size(); i++) {
sumNext(list, i, nextSum, max, currentElement);
}
}
currentElement.remove(list.get(pos));
}
}
Will output:
max=10
2 3 5
4 6
max=13
2 5 6
2 11
3 4 6
I need to write a method that takes an array of integers and checks for every element if all its divisors (except the number itself and 1) are present in this array. If yes, the method will return true.
For example, the following array will return true:
4,5,10,2
I can't think of something efficient enough to be implemented. Could you guys help me out here?
I've been thinking to iterate through every element in the array, search for all of its divisors, put them on array, return the array and then compare to the elements in the original array.
This is a possible solution and it could work but I want to know of other possible solutions.
EDIT: Here is a code I've came up with but it is super slow. Could you guys help me optimise it a little bit?:
import java.util.Arrays;
public class Divisors {
public static void main(String[] args) {
int[] numbers = { 4, 5, 10, 2 };
boolean flag = true;
for (int num : numbers) {
if (num % 2 != 0) {
for (int subNum = 1; subNum < num / 2; num += 2) {
if(num%subNum == 0 && subNum != 1) {
if(!Arrays.asList(numbers).contains(subNum)) {
flag = false;
}
}
}
} else {
for (int subNum = 1; subNum < num / 2; num++) {
if(num%subNum == 0 && subNum != 1) {
if(!Arrays.asList(numbers).contains(subNum)) {
flag = false;
}
}
}
}
}
System.out.println("Result is: "+flag);
}
}
I think the following alogorithm solves your need. I have tested it on a few cases and it seems to work.
For example the array:
int[] set = {2, 3, 4, 5, 7, 10, 11, 15, 18, 35};
executes instantly giving the answer "true". Try removing the 7 which will give the answer "false".
You call it thus:
reduce(set, 0, 0)
The principle used is to iterative recursively through the array, reducing the array through factorization of the array by each element. If you find an element which is smaller than the last factor, it means it can't be factored. This only works if the array is sorted. Once you reach the end of the array, you know all elements have been factored.
private static boolean reduce (int[] set, int index, int factor) {
// NOTE: set must be a sorted set of integers
if (index == set.length) {
return true;
} else {
int divisor = set[index];
if (divisor != 1) {
if (divisor < factor) return false;
for (int i = index; i < set.length; i++) {
while ((set[i]%divisor) == 0) {
set[i] = set[i]/divisor;
}
}
return reduce(set, index+1, divisor);
} else {
return reduce(set, index+1, factor);
}
}
}
See if it works, let me know if you run into any problems.
1.Iterate through every element in the array
2. Find in for loop its divisor
3. While doing 2), check for every divisor if it is contained in the array. If false - return false.
I am trying for too long to figure out this exersies but I am stuck here. I need to write a boolean method that will an array as argument and should return true if numbers in array are in decreasing order. Bu any time that I am trying I am having the same value or errors. Here is my code:
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i : numbers){
if(first <= i){
first = i;
return true;
}
//else{
// return false;
//}
}return false;
}
}
The problem in your code is that you cannot return true until after you went through the entire array. However, you can return false as soon as you detect an "inversion" - i.e. a situation when the number that follows the one you've seen before is greater than the prior number.
You are reasonably close to a working solution - you need to remove return true, uncomment the else, and change the final return false to return true.
To make your code more readable, rename first to prior. Also consider changing the "foreach" version of the for loop to a regular for loop that skips the initial element of the array. This would let you detect decreasing order, as opposed to non-increasing, which you currently detect.
Not sure I understand, but wouldn't this solve your issue?
public class Question1c{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
for (int i = 0; i < numbers.Length; i++){
if (i == 0)
continue;
if (numbers[i - 1] >= numbers[i])
return false;
}
return true;
}
}
You're essentially just aiming to check that the previous item in the array isn't greater than or equal to the current item in the array, aren't you?
You initialize first with numbers[0] this causes several problems:
An empty array throws IndexOutOfBoundsException
the first check automatically passes (numbers[0] <= numbers[0])
you best check the length of numbers for 0 and use a "normal" for loop (using an index).
Your return values is also the negation of what it should be.
This might solve your issue.
public class Question{
public static void main (String[] args){
int[] arr = {1, 9, 3, 4, 5, 6};
boolean product = isDecreasing(arr);
System.out.println(product);
}
public static boolean isDecreasing (int[] numbers){
int first = numbers[0];
for (int i = 1; i < numbers.length ; i++) {
if (first <= numbers[i]) {
return false;
}
first = numbers[i];
}
return true;
}
}
I am working on a homework problem that involves a heap sort implementation in java. Here is what I have so far
public class HeapSort {
public static void maxHeapify(int[] a, int i) {
int largest;
int l = 2*i;
int r = (2*i)+1;
if (l<=a.length-1 && a[l]>a[i]) {
largest = l;
}
else {
largest = i;
}
if (r<a.length-1 && a[r]>a[largest]) {
largest = r;
}
if (largest != i) {
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
maxHeapify(a,largest);
}
}
public static void buildMaxHeap(int[] a) {
for (int i=(a.length-1/2); i>=1; i--) {
maxHeapify(a,i);
}
}
public static void heapSort(int[] a) {
buildMaxHeap(a);
for (int i=a.length-1; i>=1; i--) {
int temp = a[0];
a[0] = a[i];
a[0] = temp;
maxHeapify(a,1);
}
}
Here is a main I put together to test (with output)
public static void main(String[] args) {
int[] tester = {3,2,9,45,7,15,21,11,36};
System.out.println(Arrays.toString(tester));
heapSort(tester);
System.out.println(Arrays.toString(tester));
}
[3, 2, 9, 45, 7, 15, 21, 11, 36]
[3, 45, 36, 21, 9, 15, 2, 11, 7]
I am not currently getting any errors but the output is just a bit off. Any help is very much appreciated. Thanks!
*Edited to add sample output
At a quick glance, I'd say you are missing a number of calls to maxHeapify(). It looks like you only maxHeapify() half of the heap (the half that ends in the rightmost branch), but not the rest. You must call maxHeapify() for all elements in a[0] to a[length/2].
You should move the recursive call to maxHeapify() out of the conditional for swapping. For the initial build of the heap, you must propagate all the way up to the root.
And you don't maxHeapify() the 'largest' element, but the one one level up the heap, so always i/2.
if (r<a.length-1 && a[r]>a[largest]) {
largest = r;
}
should be
if (r<=a.length-1 && a[r]>a[largest]) {
largest = r;
}
I believe you also have to call maxHeapify(a,0); instead of maxHeapify(a,1); in the last loop. Apart from that the -1/2 ordering issue in the comments mentioned above. That should do the job.