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;
  }
}

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Just remove the static keyword and create a Util3 instance in the Main method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.