Friday, 24 November 2017

Divisible Sum Pairs, Non Divisible Subset Hacker Rank Solution in C

https://www.hackerrank.com/challenges/divisible-sum-pairs/problem

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main() {
    int n,result=0;
    int k,j;
    scanf("%i %i", &n, &k);
    int *ar = malloc(sizeof(int) * n);
    for(int ar_i = 0; ar_i < n; ar_i++){
       scanf("%i",&ar[ar_i]);
    }
    for(int ar_i = 0; ar_i < n-1; ar_i++){
      for(j=ar_i+1;j<n;j++)
          if((ar[ar_i]+ar[j])%k == 0)
              result++;
    }
    printf("%d\n", result);
    return 0;
}

========================================================================
https://www.hackerrank.com/challenges/non-divisible-subset/problem


#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int max(int a,int b)
{
    if(a>b)
        return a;
    return b;
}

int nonDivisibleSubset(int k, int arr_size, int* arr) {
    // Complete this function
    int h[101]={0},result=0,i,j;
    for(i=0;i<arr_size;i++)
        h[(arr[i]%k)]++;
    if(h[0] != 0) result++;
    for(i=1,j=k-1;i<j;i++,j--)
    {
        result=result+max(h[i],h[j]);
    }
    if(k%2 == 0 && h[k/2] != 0)
        result++;
    return result;
}

int main() {
    int n;
    int k;
    scanf("%i %i", &n, &k);
    int *arr = malloc(sizeof(int) * n);
    for (int arr_i = 0; arr_i < n; arr_i++) {
       scanf("%i",&arr[arr_i]);
    }
    int result = nonDivisibleSubset(k, n, arr);
    printf("%d\n", result);
    return 0;
}

3 comments:

  1. a test case fails while submitting code as runtime error....

    ReplyDelete
    Replies
    1. no test case fails as runtime error. In this technic, we are finding count of divisors, those who give remainder 1 ...those who give reminder n-1 and solving the problem

      Delete