Code complexity [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can anybody explain to me the time complexity of the following code:
cin >> n;
while(n>9)
{
int num = n;
int s = 0;
while(num!=0)
{
s = s + num%10;
num = num/10;
}
n = s;
}
cout<<n<<endl;
The above code calculates the sum of the digits of the number until the sum becomes a single digit number.
Example: 45859 = 4+5+8+5+9 = 31 = 3+1 = 4
Edit: I think that the inner loop calculating the sum of digits has O(log_base_10(n)) complexity, but the outer loop continues till the sum obtained so far is less than 10. So the total complexity depends on how many times the outer loop is going to run.. I am not able to figure that out... Some kind of mathematical gimmicks to calculate the complexity of the outer loop would help!!!

You are calculating the sum of the digits. The number of digits in n scales with log(n).

Related

Is there a mathematical proof that says an integer 'n' can have atmost root(n) factors. Is this statement even true? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
Improve this question
Suppose if I have to perform an operation on every factor of n that takes O(n). Will its time complexity be O(n * sqrt(n)) or O(n * n) if I write the following program in C++.
for(int i=1;i<n;++i){
if(n%i==0){
Some operation of O(n);
}
}
I know there does exist a far more efficient solution but the reason I am asking this question is because I submitted this code in a contest with constraints on n<=10^5 and it got accepted. Thanks already.
You are asking about the asymptotic growth behavior of the divisor function.
Basically you can see that this code is O(n * sqrt(n)) by rewriting it as follows:
void do_linear_time_task(int divisor, int n) {
// do something that takes O(n) time...
}
void takes_sqrt_n_times_n_time(int n) {
for (int i = 1; i <= static_cast<int>(std::sqrt(n)); ++i) {
if (n % i == 0) {
int divisor_1 = i;
int divisor_2 = n / i;
if (divisor_1 == divisor_2) {
// they are the same number so just call the O(n) routine once.
do_linear_time_task(divisor_1, n);
} else {
do_linear_time_task(divisor_1, n);
do_linear_time_task(divisor_2, n);
}
}
}
}
The above will call the O(n) routine on the same numbers as the original code but in this version it is pretty clear it can't do that more than O(sqrt(n)) times.

Calculating the algorithm complexity [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
enter image description here
Pseudocode
Can you help me finding out the complexity of the algorithm, as these j <-2j; i<-i+1 throw me out a bit.
Let us first consider the inner loop :
j = 1
while j<=n
O(1)
j = 2*j
This loops runs for the values of j = 1,2,4,8,... while j<=n.
This loop will thus have logarithmic time complexity i.e O(log n).
Now consider the outer loop :
i = 2
while i<=n
O(1)
//inner loop
i = i+1
This loops run for the values of i = 2,3,,4,...,n
Thus outer loop have linear time complexity ,i.e O(n).
So total time complexity = O(n)*O(log n) = O(n*log n)

How to optimise this code of sorting,this is not exeuting within the time limits.This question is from hackerrank [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How to reduce the time compexity of this code,this is not exeuting within the time
exact ques from hackerrank--
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices to report
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
int i,temp;
vector<int> ans;
//to perform number of queries k
while(k--)
{ //shift last element to first pos and then move rest of elements to 1 postion forward
temp=a[a.size()-1]; //last element
for(i=a.size()-1;i>0;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
}
for(i=0;i<queries.size();i++)
{
ans.push_back(a[queries[i]]);
}
return ans;
}
The vector a is being rotated by k in the while loop. The whole loop can be removed by adding k and using modulo when accessing elements in a:
ans.push_back(a[(queries[i]+k)%a.size()]);
Note: you might need handling of negative values of k.
Note: Maybe it should be minus instead of plus.
An alternative could be to use std::rotate.
Furthermore, the ans vector should be pre-allocated to reduce the number of allocations to one:
ans.reserve(queries.size());

What's an algorithm to print the permutations of a string with much efficiency? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
The algorithm which I know is the below but why I hate this approach is it's time complexity is O((n+1)!) too worse in case of large strings
Start by sorting the string and printing that as the first permutation.
Now, we can find the next permutation as follows:
Let i be the last index such that input[i] < input[i + 1]. If there is no such index, then we’re done.
Let j be the last index such that input[i] < input[j].
Swap input[i] with input[j].
Reverse input[i + 1] through input[input.length - 1].
Is there any better approach than the above one ?(If explanation is through code then please consider c or c++)... just I am expecting a better algorithm with lesser time complexity than the above one
There are n! permutations for a string with length n. Simply printing them is O(n * n!), how can you expect it will be much more efficient?
Even the standard C++ implementation to print permutations of a string follows exactly same algorithm (std::next_permutation and std::prev_permutation)
std::string s;
std::sort(s.begin(), s.end());
do {
std::cout << s << std::endl;
} while(std::next_permutation(s.begin(), s.end()));
Keep in mind that in C++ the STL has std::next_permutation that does the job you need

maxi and min times to calculate the Fibonacci numbers for six seperate runs at n [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The wording for this problem has me completely confused. I know how to get "timing" using GetTickCount() but I have to repeat the calculation 6 times for each N and I have to have 6 different N and the results have to be reported in one table as max an min times. It seams to me as though this is not feasible because the run time for one N is not going to be the run time for another N. Any help is greatly appreciated. Ill post the original question below.
EDIT*: My own Frazzled brain was over complicating the problem! I got it figured out now Thanks to everyone who took time to try and help out!
'Your task is to find the maximum and minimum execution times of the Fibonacci number computation routines for six separate, unique runs at each value of n. NOTE: do not use the tail recursion implementation.'
I was thinking of perhaps storing the average run time values in arrays and then sorting those arrays to get the min and max and doing that 6 different times for both the min and max for iterative and recursive but that takes something like 24 arrays which just seems pointless.
For each input N, you need to calculate Fibb(N) six times, and display the minimum and maximum of those times. You display one minimum per N, and one maximum per N. Does it help to imagine that there are 100 N, and each one is calculated 6 times? You'd expect to see 100 minimums and 100 maximums.
For many simple competitions or homework, it looks vaguely like this:
while(std::cin >> N) {
int duration[6] = {};
int result = 0;
for(int i=0; i<6; ++i) {
auto start = GetTickCount();
int result = Fib(N);
auto end = GetTickCount();
duration[i] = end-start;
}
int max = std::max_element(std::begin(duration), std::end(duration));
int min = std::min_element(std::begin(duration), std::end(duration));
std::cout<<"Fib("<<N<<")="<<result<<" max="<<max<<" min="<<min<<'\n';
}