Reputation:
I am writing one java program in which I don't want to use any loop for array list elements.
Sure below program will print the output from 0 to n without using any loop because ArrayList inherits a toString() method with a loop in it from AbstractCollection.
import java.util.*;
class withoutloop{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<>();
int n = scan.nextInt();
for(int i=0;i<=n;i++)
arr.add(i);
System.out.println(arr);
}
}
But I want to put some calculations using each element in array list without any loop.Like the below program
import java.util.*;
class withoutloop{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> arr = new ArrayList<>();
int n = scan.nextInt();
int m = scan.nextInt();
int count = 0;
for(int i=0;i<=n;i++)
arr.add(i);
for(int i=2;i<=m;i++){
Iterator it = arr.iterator();
while(it.hasNext()){
Integer element = it.next();
if(element%i==0)
count++;
}
}
System.out.println(count);
}
}
Now if I use this program this will give me approximately O(n*m) solution which I don't want. Is there any way I can access all elements in array list without using any loop ?
Upvotes: 0
Views: 105
Reputation: 33496
Java 8 can make your code simpler using IntStream.rangeClosed
, but there is little you can do to avoid having an O(n*m) solution without devising a smarter algorithm.
long count = IntStream.rangeClosed(0, n)
.mapToLong(element -> IntStream.rangeClosed(2, m)
.filter(i -> element % i == 0)
.count())
.sum();
System.out.println(count);
Previous to Java 8, the equivalent code would be something like:
long count = 0;
for (int element = 0; element <= n; element++) {
for (int i = 2; i <= m; i++) {
if (element % i == 0) {
count++;
}
}
}
System.out.println(count);
Upvotes: 1