Gcd method

by JaysFan31
Tags: method
 P: n/a I am a beginner programmer in Java. Just started learning the past few weeks. I'm taking a class and need to create a method that finds the greatest common divisor of two integers. I can assume that both are positive, but I cannot use the Euclidean Algorithm. I'm sort of lost, but I think I'm on the right track, although this may look confusing: public static int gcd(int a, int c) { int gcd; int attempt; if (a > c) { if (a % c == 0) { gcd = c; return gcd; } else { for (attempt = c; attempt = 1; attempt--) do { if (c % attempt == 0 && a % attempt == 0) { gcd = attempt; return attempt; } } while (c % attempt != 0 || a % attempt == 0); } } And then I basically copied the code with an else statement if c > a. I'm sure there are a lot of mistakes. Could someone just point them out and offer a simpler way of doing it (possibly without using the Euclidean Algorithm)? Thanks. Michael
 P: n/a Gcd method OK. I think this is a lot better. It compiles and makes sense to me at least. However, it doesn't work properly for more difficult integers like 20, 30. Can anyone spot the problem (as I said nothing wrong with compiling, just doesn't work logically). As I said before, I can't use the Euclidean Algorithm, so I basically had to write the simplest program to find gcd. public static int gcd(int a, int b) { int gcd; if (a > b && a % b == 0) { gcd = b; return gcd; } else if (b > a && b % a == 0) { gcd = a; return gcd; } else if (a > b && a % b != 0) { int count = b; do { count = count - 1; } while (b % count != 0 && a % count != 0); gcd = count; return gcd; } else if (b > a && b % a != 0) { int count = a; do { count = count - 1; } while (b % count != 0 && a % count != 0); gcd = count; return gcd; } else { gcd = a; return gcd; } }