Time Complexity of Loop with Powers Last Updated : 23 Aug, 2024 Comments Improve Suggest changes 49 Likes Like Report What is the time complexity of the below function? C++ void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = pow(i, k); for (int j = 1; j <= p; j++) { // Some O(1) work } } } // This code is contributed by Shubham Singh C void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = pow(i, k); for (int j = 1; j <= p; j++) { // Some O(1) work } } } Java static void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = Math.pow(i, k); for (int j = 1; j <= p; j++) { // Some O(1) work } } } // This code is contributed by umadevi9616 Python def fun(n, k): for i in range(1, n + 1): p = pow(i, k) for j in range(1, p + 1): # Some O(1) work # This code is contributed by Shubham Singh C# static void fun(int n, int k) { for (int i = 1; i <= n; i++) { int p = Math.Pow(i, k); for (int j = 1; j <= p; j++) { // Some O(1) work } } } // This code is contributed by umadevi9616 JavaScript <script> // JavaScript program for the above approach function fun(n, k) { for(let i = 1; i <= n; i++) { int p = Math.pow(i, k); for (let j = 1; j <= p; j++) { // Some O(1) work } } } // This code is contributed by Shubham Singh </script> Time complexity of above function can be written as 1k + 2k + 3k + ... n1k.Let us try few examples: k=1Sum = 1 + 2 + 3 ... n = n(n+1)/2 = n2/2 + n/2k=2Sum = 12 + 22 + 32 + ... n12. = n(n+1)(2n+1)/6 = n3/3 + n2/2 + n/6k=3Sum = 13 + 23 + 33 + ... n13. = n2(n+1)2/4 = n4/4 + n3/2 + n2/4 In general, asymptotic value can be written as (nk+1)/(k+1) + Θ(nk)If n>=k then the time complexity will be considered in O((nk+1)/(k+1)) and if n<k, then the time complexity will be considered as in the O(nk) Create Quiz Comment K kartik Follow 49 Improve K kartik Follow 49 Improve Article Tags : Analysis of Algorithms DSA time complexity Explore DSA FundamentalsLogic Building Problems 2 min read Analysis of Algorithms 1 min read Data StructuresArray Data Structure 3 min read String in Data Structure 2 min read Hashing in Data Structure 2 min read Linked List Data Structure 3 min read Stack Data Structure 2 min read Queue Data Structure 2 min read Tree Data Structure 2 min read Graph Data Structure 3 min read Trie Data Structure 15+ min read AlgorithmsSearching Algorithms 2 min read Sorting Algorithms 3 min read Introduction to Recursion 15 min read Greedy Algorithms 3 min read Graph Algorithms 3 min read Dynamic Programming or DP 3 min read Bitwise Algorithms 4 min read AdvancedSegment Tree 2 min read Binary Indexed Tree or Fenwick Tree 15 min read Square Root (Sqrt) Decomposition Algorithm 15+ min read Binary Lifting 15+ min read Geometry 2 min read Interview PreparationInterview Corner 3 min read GfG160 3 min read Practice ProblemGeeksforGeeks Practice - Leading Online Coding Platform 1 min read Problem of The Day - Develop the Habit of Coding 5 min read Like