In this HackerRank Viral Advertising problem, you need to determine how many people have liked the ad by the end of a given day, beginning with launch day as day 1.

HackerRank Viral Advertising problem solution


Problem solution in Python programming.

import math
input_str = input()
try:
    nbr = int(input_str)
except:
    print("An exception occurred while parsing input as integer.")
if nbr <= 0 or nbr >= 51:
    print("Bad input specified")
result = 0
people = 5
for day in range(1, nbr + 1):
    half = math.floor(people / 2)
    result += half
    people = 3 * half
print(result)


Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
         Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int received = 5;
        int sum=0;
        while(n-- >0){
            int remaining = received/2;
            sum+=remaining;
            received = remaining*3;
        }
        System.out.println(sum);

    }
}


Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;



int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    int n;
    cin>>n;
    
    int m = 5;
    int total;
    for(int i=0; i<n; ++i){
        m = m/2;
        total += m;
        m *= 3;
    }
    
    cout<<total<<endl;
    return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{

    int n,i,t1=0,t2=0,sum=0,m=5;
    scanf("%d",&n);
    
    for(i=0;i<n;i++)
    {
        t1 = m/2;
        m = t1*3;
        sum += t1;
    }
    
    printf("%d",sum);
    
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}


Problem solution in JavaScript programming.

function processData(input) {
    var n = parseInt(input), result = 0;
    
    function totalLikes(people, n){
        var liked = Math.floor(people / 2);
        result += liked;
        if(n > 1){
            totalLikes(liked * 3, --n);
        }
    }
    
    totalLikes(5, n);
    
    console.log(result);    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});