Many ongoing research activities relevant to 5G mobile systems concern the virtualization of the mobile core network, including the evolved packet core (EPC) elements, aiming for system scalability, elasticity, flexibility, and cost-efficiency. Virtual EPC (vEPC)/5G core will principally rely on some key technologies, such as network function virtualization, software defined networking, and cloud computing, enabling the concept of mobile carrier cloud. The key idea beneath this concept, also known as core network as a service, consists in deploying virtual instances (i.e., virtual machines or containers) of key core network functions [i.e., virtual network functions (VNF) of 4G or 5G], such as the mobility management entity (MME), Serving GateWay (SGW), Packet Data network gateWay (PGW), access and mobility management function (AMF), session management function (SMF), authentication server function (AUSF), and user plane functions, over a federated cloud. In this vein, an efficient VNF placement algorithm is highly needed to sustain the quality of service (QoS) while reducing the deployment cost. Our contribution in this paper is twofold. First, we devise an algorithm that derives the optimal number of virtual instances of 4G (MME, SGW, and PGW) or 5G (AMF, SMF, and AUSF) core network elements to meet the requirements of a specific mobile traffic. Second, we propose an algorithm for the placement of these virtual instances over a federated cloud. While the first algorithm is based on mixed integer linear programming, the second is based on coalition formation game, wherein the aim is to build coalitions of cloud networks to host the virtual instances of the vEPC/5G core elements. The obtained results clearly indicate the advantages of the proposed algorithms in ensuring QoS given a fixed cost for vEPC/5G core deployment, while maximizing the profits of cloud operators.