From f174c93136d14c1f7abb3ff891c22beb3503e28e Mon Sep 17 00:00:00 2001 From: Akshat2806 Date: Fri, 2 Oct 2020 12:16:24 +0530 Subject: [PATCH] Optimized code to reduce time complexity changed the traversing of factors to sqrt(n) to reduce time complexity to o(sqrt(n)). --- General/Prime.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/General/Prime.cpp b/General/Prime.cpp index 6ede07e..05079a8 100644 --- a/General/Prime.cpp +++ b/General/Prime.cpp @@ -8,8 +8,12 @@ int main() cout << "Enter a positive integer: "; cin >> n; + + //factors exist in pair,so traversing till sqrt(n) to reduce time complexity + //Time Complexity: O(sqrt(n)) + //Space Complexity:O(1) - for(i = 2; i <= n / 2; ++i) + for(i = 2; i*i<=n; i++) { if(n % i == 0) {