home

Scientific Computing (Psychology 9040a)

Fall, 2021

Project Euler Problem 37: Sample solution


%% Project Euler Problem 37

tp = zeros(1,11);

i = 0;
n = 9;

while (i < 11)
    if isprime(n)
        ns = num2str(n);
        truncatable = true;
        while (length(ns)>1) % left->right chop
            if isprime(str2num(ns(2:end)))
                ns = ns(2:end);
            else
                truncatable = false;
                break
            end
        end
        if truncatable==true % only continue if left->right chop passed
            ns = num2str(n);
            while (length(ns)>1) % right->left chop
                if isprime(str2num(ns(1:end-1)))
                    ns = ns(1:end-1);
                else
                    truncatable = false;
                    break
                end
            end
            if truncatable==true
                i = i + 1;
                tp(i) = n;
            end
        end
    end
    n = n + 2;
end

fprintf("the answer is %d\n", sum(tp));