Algorithm


Problem Name: Mathematics - Sherlock and Divisors

Problem Link: https://www.hackerrank.com/challenges/sherlock-and-divisors/problem?isFullScreen=true

In this HackerRank in Mathematics - Sherlock and Divisors solutions,

Watson gives an integer N to Sherlock and asks him: What is the number of divisors of N that are divisible by 2?.

Input Format
First line contains T, the number of testcases. This is followed by T lines each containing an integer N.

Output Format
For each testcase, print the required answer in one line.

Constraints

1 <= T <= 100

1 <= N <= 109

Sample Input

2
9
8

Sample Output

0
3

Explanation
9 has three divisors 1, 3 and 9 none of which is divisible by 2.
8 has four divisors 1,2,4 and 8, out of which three are divisible by 2.

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <stdio.h>
#include <math.h>
int main()
{
    int n,i,t,c;
    scanf("%d",&t);
    while(t--)
    {
        c=0;
        scanf("%d",&n);
        for(i=1;i < =sqrt(n);i++)
        {
            if(n%i == 0)    //i is divisor of n
            {
                if(i%2 == 0)   //even divisor
                                c++;
                if((n/i)%2 == 0 && (n/i)!=i)   //if i is divisor of n then n/i is also divisor of n
                                c++;
            }
        }
        printf("%d\n",c);
    }             
    
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

/*
 * Complete the 'divisors' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts INTEGER n as parameter.
 */

int divisors(int n) {
    int ans = 0;

    for(int i = 1; i * i  < = n; i++) {
        if(n % i == 0) {
            if(i%2==0)ans++;
            if(i * i != n) {
                if((n/i)%2==0)ans++;
            }
        }
    }
    return ans;

}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string t_temp;
    getline(cin, t_temp);

    int t = stoi(ltrim(rtrim(t_temp)));

    for (int t_itr = 0; t_itr < t; t_itr++) {
        string n_temp;
        getline(cin, n_temp);

        int n = stoi(ltrim(rtrim(n_temp)));

        int result = divisors(n);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(>, not1(ptr_fun < int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun < int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

Copy The Code & Try With Live Editor

#3 Code Example with C# Programming

Code - C# Programming


using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;

class Result
{

    /*
     * Complete the 'divisors' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER n as parameter.
     */

    public static int divisors(int n)
    {
        var sqrt = Math.Sqrt(n);
        var count = 0;
        
        for(int i = 1; i  < = sqrt; i++){
            var remainder = n % i;
            if(remainder == 0){
                var div2 = n / i;
                count =   i  % 2 == 0 ? ++count : count;
                if(div2 != i){
                    count = div2 % 2 == 0 ? ++count : count;
                }                
            }
        }
        
        return count;

    }

}

class Solution
{
    public static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int t = Convert.ToInt32(Console.ReadLine().Trim());

        for (int tItr = 0; tItr < t; tItr++)
        {
            int n = Convert.ToInt32(Console.ReadLine().Trim());

            int result = Result.divisors(n);

            textWriter.WriteLine(result);
        }

        textWriter.Flush();
        textWriter.Close(>;
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Java Programming

Code - Java Programming


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

class Result {

    /*
     * Complete the 'divisors' function below.
     *
     * The function is expected to return an INTEGER.
     * The function accepts INTEGER n as parameter.
     */

    static int divisors(int n) {
        /*
         * Write your code here.
         */
        int count = 0;
        if(n%2 != 0){
            return count;
        }
        int i =2,j = n/2;
        while(j >= i){

            if(n % i ==0 && i %2 == 0){
                count++;
            }
            if(n %j == 0 && i != j && j %2==0){
                count++;

            }
            i += 1;
            j = n/i;

        }

        return count +1;

    }

}

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int t = Integer.parseInt(bufferedReader.readLine().trim());

        IntStream.range(0, t).forEach(tItr -> {
            try {
                int n = Integer.parseInt(bufferedReader.readLine().trim());

                int result = Result.divisors(n);

                bufferedWriter.write(String.valueOf(result));
                bufferedWriter.newLine();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        bufferedReader.close();
        bufferedWriter.close();
    }
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'divisors' function below.
#
# The function is expected to return an INTEGER.
# The function accepts INTEGER n as parameter.
#

def divisors(n):
    # Write your code here
    i = 0
    for x in range(1,int(math.sqrt(n))+1):
        if n%x==0:
            if x%2==0:
                i += 1
            if (n/x)%2==0 and x**2!=n:
                i += 1
    return i

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    t = int(input().strip())

    for t_itr in range(t):
        n = int(input().strip())

        result = divisors(n)

        fptr.write(str(result) + '\n')

    fptr.close()

Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Strange Grid Again solution in Hackerrank - Hacerrank solution C, C++, C#, java, js, Python
Next
[Solved] Halloween party solution in Hackerrank - Hacerrank solution C, C++, C#, java, js, Python