Search

# C Program to find a number having max sum of divisors & also its position in the array

Write a C program that reads an unspecified number of integers from a file called nums.txt (up to a maximum of 100 numbers) and stores those numbers in an array. The program should display the number with maximum sum of divisors as well as its position in the array.

Example of Sample Run:

Assume that the file nums.txt has the following 6 numbers (nums.txt can have up to a 100 numbers, which means the array should be defined as 100 ) :

Input:

53 61 40 83 49 44

Output:

The number with max sum of divisors is 40 at position 2 in the array.

Code:

#include <stdio.h>

int* max_sum_and_pos(int arr[], int);

int sum_of_divs(int n);

int main(){

FILE *fp;

int arr, *max_detail, i = 0;

fp = fopen("nums.txt","r");

if (fp == NULL){

printf("File is empty!!!");

}

else{

while(!feof (fp)){

fscanf (fp, "%d", &arr[i]);

i++;

}

}

fclose(fp);

max_detail = max_sum_and_pos(arr, i);

printf("The number with max sum of divisors is %d at position %d in the array.",max_detail,max_detail);

return 0;

}

/*** Finding the number having max sum of divs. from the array ***/

int* max_sum_and_pos(int arr[], int n){

int divs_arr[n], m_dtl, j, *pt;

for(j = 0; j < n; j++){

divs_arr[j] = sum_of_divs(arr[j]);

}

int max = divs_arr;

for(int k = 0; k < n; k++){

if(divs_arr[k] > max){

max = divs_arr[k];

j = k;

}

}

m_dtl = arr[j];

m_dtl = j;

pt = m_dtl;

return pt;

}

/*** Evaluating the sum of divisors of a number ***/

int sum_of_divs(int n){

int sum = 0;

for(int i = 1; i <= n; i++){

if(n % i == 0){

sum = sum + i;

}

}

return sum;

}

### Recent Posts

See All

#### Highest Divisor - CodeChef Solution | AskTheCode

CodeChef Feb Long Challenge Solution - Highest Divisor in C | Ask The Code...You are given an integer N. Find the largest integer...more

#### Enormous Input Test - CodeChef Solution in C | AskTheCode

CodeChef Practice Problem Solution in C Programming...Ask The Code...The purpose of this problem is to verify whether the method...Read more

#### C Program To Add Two User Given Polynomials

C program to add two polynomials | Ask The Code C Program to find the result of addition of two given polynomials by the user...Read more...