0

I've been having some issues trying to solve this code that my professor sent to me for studying purposes. I usually can solve the isPrime and getPrime no problem but my issue lies with the gcd class. Would love to get some input on this. Thanks :) Sorry for the formatting since i'm new to the site

import java.util.*;

public class Util3
{
  public ??? getSmaller(???)
  {
    int smaller;
    if (???)
      smaller = ???;
    else
      smaller = ???;

    return smaller;
  }

  public ??? gcd(??? a, ??? b)
  {
    int g, smaller;

    smaller = ???(a, b);
    g = smaller;
    for (int i = ???; i >= 1; i++) {  // from smaller to 1
      if (a % i == 0 ??? ???) {
        g = i;
        ???;
      }
    }

    return g;
  }

  public ??? isPrime(int p)
  {
    if (p < 2)
      return false;

    int i;
    for (i = ???; i <= ???; i++)  // from 2 to p-1
      if (??? == 0)  // if p is divisible by i
        break;

    if (i == ???)
      return ???;
    else
      return ???;
  }

  public ??? getPrime(int n)
  {
    boolean b;
    int p;

    for (p = n+1; ; p++) {  // n+1, n+2, ...
      b = ???(p);  // check if p is a prime number
      if (???)
        break;
    }

    return p;
  }
}
Kowalchu1
  • 11
  • 1

1 Answers1

0

You can use a naive solution:

public static int gcd(int a, int b) {
    int current_gcd = 1;
    for(int d = 2; d <= a && d <= b; ++d) {
      if (a % d == 0 && b % d == 0) {
        if (d > current_gcd) {
          current_gcd = d;
        }
      }
    }
    return current_gcd;
  }

Or a recursive one:

public static int GCD(int a, int b) {
    if (b == 0) {
        return a;
        }
     }
    return GCD(b, a % b);
}
Nooblhu
  • 552
  • 15
  • 33
  • Thanks for the input! what about a non-static method? It definitely works a lot better but where i am currently in the unit hasn't required a static method involved in the class yet. – Kowalchu1 Nov 20 '16 at 03:34
  • Just remove the static keyword and create a Util3 instance in the Main method – Nooblhu Nov 20 '16 at 03:36