Q:

C Program to find given number is the sum of first n natural numbers using Binary Search

belongs to collection: C Programming on Numbers

0

C Program to find given number is the sum of first n natural numbers using Binary Search

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include <stdio.h>
int findSum(int data)
{
    int l = 1, r = (data / 2) + 1;
    int isEqual = 0;
    // Apply Binary search
    while (l <= r)
    {
        // Find mid
        int mid = (l + r) / 2;
        // find sum of 1 to mid natural numbers
        // using formula
        int sum = mid * (mid + 1) / 2;
        // If sum is equal to n
        // return mid
        if (sum == data)
        {
            isEqual= mid;
            break;
        }
        // If greater than n
        // do r = mid-1
        else if (sum > data)
        {
            r = mid - 1;
        }
        // else do l = mid + 1
        else
        {
            l = mid + 1;
        }
    }
    return isEqual;
}
int main()
{
    int data = 15, isSumOfNaturalNumber = 0;
    printf("Enter number = ");
    scanf("%d", &data);
    isSumOfNaturalNumber = findSum(data);
    if(isSumOfNaturalNumber)
    {
        printf ("Sum of Natural number 1 to %d\n",isSumOfNaturalNumber);
    }
    else
    {
        printf("It is not a sum of 1 to n Natural number\n");
    }
    return 0;
}

Output:
Enter number = 10
Sum of Natural number 1 to 4

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C Programming on Numbers

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C Program to swap two numbers using a third variab... >>
<< C Program to find the sum of odd numbers within a ...