There are n pencils, each having l length. Each can write 4 kilometers. After writing 4 kilometers it has l/4 length. One can join 4 pencils which are having l/4 length and can make 1 pencil. One can’t make pencil of pieces if remaining pieces are 3 or 2 or 1 in number but one can include these remaining pieces whenever needed.
Write a relation independent of l,length of given pencil, for how much one can write from n pencils.
Examples :
Input : 4 Output : 20
Approach:
Suppose We use 3 pencils that will 12 and generate 3 used pencils, now if the remaining pencils are greater than zero at least 1 unused pencil can be used with those 3 unused to write 4 and that will generate 1 more unused pencil. This will keep repeating.
if(n-3 >= 1){
f(n) = f(n-3) + 12 + 4
} else{
f(n) = 4*n
}
Above relation can be optimized in O(1)
n - 3 + x <= 3 //x is max no of time we can subtract 3 without n-3 <= 3
x > (n-3)/3
ie. n/3 - 1 if it divides exactly else n/3
//C++ program to find relation independent of l,length of given pencil, for how much one can write from n pencils.
#include<bits/stdc++.h>
using namespace std;
//Function to find no of pencils
int count(int n){
int x = (n/3) - 1;
if(n%3){
x++;
}
return (4*x + 4*n);
}
//Driver function
int main(){
int n = 5;
cout<<count(n)<<endl;
}
Output :
24
Recursively it can be written as:
int count(int n){
if(n<4){
return (n*4);
} else{
return (16+count(n-3));
}
}