Home > Enterprise >  How to find the maximum distance in a set on consecutive prime numbers?
How to find the maximum distance in a set on consecutive prime numbers?

Time:10-26

I am writing a method that finds the largest distance in a consecutive set of prime numbers. For example, if the set is 2,3,5,7,11,13,17,19,23,29; the method would return 6 because the greatest distance within the set is 6 (23-29).

My code so far is:

 public static double primeSpace(int n)
{
    int i = 0;
    int Prime1;
    int Prime2;
    while (i <= 0)
    {
        for(; i <= n; i  )
        {
            if (isPrime(n))
            {
                Prime1 = n;
                
            }
        }
    }

}

So as is obvious, I am not sure of how to store a value for prime2 so I can subtract and after that I am lost.

CodePudding user response:

You do not need a double loop, think about the problem, what you are doing is only calculating the differenct between a number and the one after it.

You only need to store one local variable max, assign a new value to max each time the difference is bigger than max.

It is also unclear what your input is, where does the list of primes come from>? Is n the size of the list of primes starting from 2?

CodePudding user response:

I think you want code like this:

    List<Integer> primeList = new ArrayList<>();
    primeList.add(2);
    primeList.add(3);
    primeList.add(5);
    primeList.add(7);
    primeList.add(11);
    primeList.add(13);
    primeList.add(17);
    primeList.add(19);
    primeList.add(23);
    primeList.add(29);

    int distance = 0;
    for(int i=1;i <primeList.size();i  ) {
        int tempDistance = primeList.get(i)-primeList.get(i-1);
        if (tempDistance>distance) {
            distance = tempDistance;
        }
    }
    System.out.println(distance);
}
  • Related