When you can, build a list rather than pick it out of a larger list

Image for post
Image for post
Photo by Glenn Carstens-Peters on Unsplash
    public static List<Integer> _______(int threshold) {
List<Integer> nums = new ArrayList<>();
for (int i = 0; i <= threshold; i++) {
nums.add(i);
}
for (int j = threshold; j > -1; j--) {
if (nums.get(j) % 4 != 1) {
nums.remove(j);
}
}
return nums;
}
   public static List<Integer> _______(int threshold) {
List<Integer> nums = new ArrayList<>();
for (int i = 1; i <= threshold; i++) {
if (i % 4 == 1) {
nums.add(i);
}
}
return nums;
}
scala> var threshold = 50
threshold: Int = 50
scala> for (i <- 1 to threshold if i % 4 == 1) yield i
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49)
scala> threshold = 687
threshold: Int = 687
scala> for (i <- 1 to threshold if i % 4 == 1) yield i
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69, 73, 77, 81, 85, 89, 93, 97, 101, 105, 109, 113, 117, 121, 125, 129, 133, ...
    public static List<Integer> _______(int threshold) {
List<Integer> nums = new ArrayList<>();
int curr = 1;
while (curr <= threshold) {
nums.add(curr);
curr += 4;
}
return nums;
}
scala> threshold = 50 // Resetting to previous value
threshold: Int = 50
scala> 1 to threshold by 4
res2: scala.collection.immutable.Range = inexact Range 1 to 50 by 4
    public static List<Integer> _______p_(int threshold) {
List<Integer> primes = new ArrayList<>();
for (int i = 0; i <= threshold; i++) {
primes.add(i);
}
for (int j = threshold; j > -1; j--) {
if (!isPrime(primes.get(j)) || primes.get(j) % 4 != 1) {
primes.remove(j);
}
}
return primes;
}
    public static List<Integer> _______p_(int threshold) {
List<Integer> primes = _______(threshold);
for (int i = primes.size() - 1; i > -1; i--) {
if (!isPrime(primes.get(i))) {
primes.remove(i);
}
}
return primes;
}
    public static List<Integer> _______p_(int threshold) {
List<Integer> primes = sieve(threshold);
for (int i = primes.size() - 1; i > -1; i--) {
if (primes.get(i) % 4 != 1) {
primes.remove(i);
}
}
return primes;
}

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store