I tried to have the same counter for the AMS and algorithm2e algorithm-environment with
\usepackage{aliascnt}
\makeatletter
\let\c@algocf\relax
\makeatother
\newaliascnt{algocf}{thm}
as described here Share counter between amsthm and algorithm.
Here is my MWE code. It is created with Lyx, as this is what I use for my thesis.
%% LyX 2.1.4 created this file. For more info, see http://www.lyx.org/.
%% Do not edit unless you really know what you are doing.
\documentclass[english]{article}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\usepackage{amsmath}
\usepackage{amsthm}
\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
\theoremstyle{plain}
\newtheorem{thm}{\protect\theoremname}
\theoremstyle{plain}
\newtheorem{lyxalgorithm}[thm]{\protect\algorithmname}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
% algorithms
\usepackage[linesnumbered,algoruled,boxed,lined,english]{algorithm2e}
\usepackage{aliascnt}
\makeatletter
\let\c@algocf\relax % drop existing counter
\makeatother
\newaliascnt{algocf}{thm}
\makeatother
\usepackage{babel}
\providecommand{\algorithmname}{Algorithm}
\providecommand{\theoremname}{Theorem}
\begin{document}
\begin{lyxalgorithm}
\label{alg1}
Do stuff.
\end{lyxalgorithm}
\begin{algorithm}[H]
\label{alg2}
Do other stuff.
\caption{$\leftarrow$ Prints the correct number 2}
\end{algorithm}
\begin{lyxalgorithm}
\label{alg:alg3}
Just be!
\end{lyxalgorithm}
Here is a reference to Algorithm \ref{alg1}, Algorithm \ref{alg2} and Algorithm \ref{alg:alg3}.
\end{document}
How do I make \ref{alg2} print the correct number 2 instead of 1?
\labelhas to be after\captionif you want it to use the captions number. – David Carlisle Sep 23 '16 at 10:18