Calculate the Cyclomatic Complexity

318 Views Asked by At

Calculate the CC (Cyclomatic Complexity) of the following code snippets.

I am not sure if I have drawn the Control Flow Graph correctly and furthermore if my calculation for the Cyclomatic Complexity is correct. And as for the formula M = E - N + 2P, the P is defined as "P = number of nodes that have exit points". Am I only counting the return here? How is it then with GCD2, if the method calls itself recursively does this also count as a return?

GCD1

public class GCD1 {
    public int gcd(int a, int b) {
        if (a < b) {
            int t = a;
            a = b;
            b = t;
        }
        while (a % b != 0) {
            int r = a % b;
            a = b;
            b = r;
        }
        return b;
    }
}

GCD2

public class GCD2 {
    public int gcd(int a, int b) {
        if (a < b)
            return gcd(b, a);
        else if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
}

Calculation

M = E – N + 2P

where,

  • E = the number of edges in the control flow graph
  • N = the number of nodes in the control flow graph
  • P = number of nodes that have exit points

Control Flow Graph of above GCD1

M = 7 - 6 + 2*1 = 3

enter image description here

Control Flow Graph of above GCD2

M = 8 - 7 + 2*1 = 3

enter image description here

0

There are 0 best solutions below