-3

I have a block of code that I've written to give me the largest prime factor of any number.

  public static void main(String[] args) {

      long n = 49;
      while (true) {
          long x = sPrimeFactor(n);
          if (x < n) n /= x;
          else 
              System.out.println(n);
      }

  }

  public static long sPrimeFactor (long n){
      if (n <= 1) return 1;
      long cap = (long) Math.sqrt(n);
              for (long i = 2; i <= cap; i++) {
                  if (n % i == 0) return i;
              }
              return n;
  }

As you might imagine, this locks into an endless loop where the largest prime factor of the number will just keep looping through the function.

How do I break it off when my solution has been reached?

EDIT: This was me just being silly. I should have searched it up first. In any case, this was the code that solved it:

public static void main(String[] args) {

      long n = (long) 49;
      while (true) {
          long p = sPrimeFactor(n);
          if (p < n) n /= p;
          if (p == n) break;
      }
      System.out.println(n);

  }

  public static long sPrimeFactor (long n){
      if (n <= 1) return 1;
      long cap = (long) Math.sqrt(n);
              for (long i = 2; i <= cap; i++) {
                  if (n % i == 0) return i;
              }
              return n;
  }
Thev
  • 1,105
  • 2
  • 13
  • 24

1 Answers1

0
while (true) {}

You need set a flag that make the while loop stop after you achieved your goal.

Or use break; is another way

OPK
  • 4,120
  • 6
  • 36
  • 66