How do I determine if a integer in a Java Intstream is of the form 3x+1?

Viewed 126

The question I was given is:

Find and print (one per line) those values of a that are of the form 3x+ 1 for some x. Each such value should be printed only once, in the position it first appears.

I have tried many variations of modulo to try and get the correct numbers but I can't seem to wrap my head around the problem.

This is the code I was given to start:

import java.util.*;
import java.util.stream.*;

class Example {

  public static void main(String argv[]) {
    int a[] =
      Arrays.stream(argv)
      .mapToInt(s -> Integer.parseInt(s))
      .toArray();
  }
      // fill in here with expression starting Arrays.stream(a)

}

Thanks for any help.

1 Answers

If a has the form 3x + 1 then a - 1 = 3x and thus you want to subtract one from each value and then test if the remainder with division would be zero. Then print the matches. Also, you could use Integer::parseInt and I would prefer the form int[] a over int a[] (the second form was preserved to be familiar to C and C++ developers) and (as pointed out by ernest_k in a comment use a distinct() to ensure uniqueness). Like,

int[] a = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();
Arrays.stream(a).filter(x -> (x - 1) % 3 == 0)
        .distinct().forEach(System.out::println);
Related