Volume program in C

Q1> Given a fixed volume of cylinder find all the possible combination of radius and height from the given input array.
Volume of cylinder is pir^2h where pi will be 22/7
First input will be n.
Next line contains n elements of array
Next line contains volume of cylinder

In each line print “R H” where R is radius , H is height found.

1 2 7

1 7

I can think of O(nLog(n)) solution. Sort given array, and as Volume is given then I can write h = V/(\pi * r^2) and for r just iterate over given array and for each r find calculated h in found sorted array in O(log(n)).

Hope this will help.

import math
n = input()
a = sorted(map(int,raw_input().split()))
dict = {i:True for i in a}
v = input()
for r in a:
    h = (v*7.0)/(22.0*r*r)
    if h in dict:
        print r,int(h)

For this particular problem, two solutions can be thought of 1st is a brute force where you’ll be generating all possible pairs in the array. O(n^2)

The second approach would be to sort the array and assume volume to V, r as radius than h = V/(pi*r^2) where you perform a linear search on r to find h and then you can do a binary search to find for that particular r, h exist in the array. O(nlog(n))

Important Note - don’t solve this problem in double or float instead take every variable integer by multiplying some constant both sides.

Hope this helps!

Use s = set(a) instead of dict = {i:True for i in a}. You don’t need a dictionary.