Skip to content

Instantly share code, notes, and snippets.

@yao2030
Created November 2, 2012 02:31
Show Gist options
  • Save yao2030/3998335 to your computer and use it in GitHub Desktop.
Save yao2030/3998335 to your computer and use it in GitHub Desktop.
test whether an integer M and another M are relative primes.
public class RelativePrime
{
public static int max(int M, int N)
{
return M >= N ? M : N;
}
public static int min(int M, int N)
{
return M <= N ? M : N;
}
public static boolean isRelativePrime(int M, int N)
{
if (M == 0 || N == 0)
return false;
if ( M == 1 || N == 1)
return false;
int k = min(M, N);
for (int i = 2; i <= k; i++)
{
if (M % i == 0 && N % i == 0)
return false;
}
return true;
}
public static boolean[][] relativePrime(int N)
{
boolean[][] a = new boolean[N][N];
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
a[i][j] = isRelativePrime(i, j);
return a;
}
public static void show(boolean[][] a)
{
int N = a.length;
StdDraw.setXscale(-1, N);
StdDraw.setYscale(-1, N);
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
{
if(a[i][j])
{
StdDraw.setPenColor(StdDraw.BLACK);
}
else
{
StdDraw.setPenColor(StdDraw.BLUE);
}
StdDraw.filledSquare(j, N-1-i, .5);
}
}
public static void main(String[] args)
{
int N = Integer.parseInt(args[0]);
boolean[][] a = relativePrime(N);
show(a);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment