function [ x m ] = MyCG(A, b)
%MyCG performs CG iterations, starting from 0

n=size(A,1);
x=zeros(n, 1);
r=b-A*x;
s=r;
r_norm_sq = r'*r;
for k=1:n
    w=A*s;
    den = s'*w;
    if den <= 0
        str=sprintf('ERROR: den = %6.4g', den);disp(str)
        break
    end
    alpha = (r'*s)/den;
    x = x + alpha*s;
    r = r - alpha*w;
    prev_r_norm_sq = r_norm_sq;
    r_norm_sq = r'*r;
    beta = r_norm_sq/prev_r_norm_sq;
    s = r + beta*s;
    if norm(r,2) <= 1e-8
        break
    end
end
m = k;
end

