From e6dbf26b85bc3bbe38bf1b3151cb3db422e61543 Mon Sep 17 00:00:00 2001 From: Ishita Mukherjee Date: Sun, 21 Jul 2024 00:01:10 +0530 Subject: [PATCH] Nth Root of M of gfg problem is added --- .../Easy problems/Nth-Number-Of-Root.md | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 dsa-solutions/gfg-solutions/Easy problems/Nth-Number-Of-Root.md diff --git a/dsa-solutions/gfg-solutions/Easy problems/Nth-Number-Of-Root.md b/dsa-solutions/gfg-solutions/Easy problems/Nth-Number-Of-Root.md new file mode 100644 index 000000000..df8984da5 --- /dev/null +++ b/dsa-solutions/gfg-solutions/Easy problems/Nth-Number-Of-Root.md @@ -0,0 +1,136 @@ +--- +id: nth-root-of-m +title: Nth root of M +sidebar_label: Nth-root-of-M +tags: + - Mathematical + - Algorithm +description: "This tutorial covers the solution to the Nth root of M problem from the GeeksforGeeks." +--- +## Problem Description +You are given 2 numbers `(n, m)`; the task is to find `n√m` (`nth` root of `m`). + + +## Examples + +**Example 1:** + +``` +Input: n = 2, m = 9 +Output: 3 +Explanation: 3^2 = 9 +``` + +**Example 2:** + +``` +Input: n = 3, m = 9 +Output: -1 +Explanation: 3rd root of 9 is not +integer. +``` + +## Your Task + +You don't need to read or print anyhting. Your task is to complete the function NthRoot() which takes n and m as input parameter and returns the nth root of m. If the root is not integer then returns -1. + + +## Constraints + +* `1 <= n <= 30` +* `1 <= m <= 10^9` + +## Problem Explanation +You are given 2 numbers (n , m); the task is to find n√m (nth root of m). + +## Code Implementation + + + + + + ```py + import math + +n = 3 +m = 27 +result = m ** (1/n) +print(result) + + ``` + + + + + + ```cpp + #include +#include + +int main() { + int n = 3; + int m = 27; + double result = pow(m, 1.0 / n); + std::cout << result << std::endl; + return 0; +} + + ``` + + + + + + + ```javascript + +function nthRoot(n, m) { + return Math.pow(m, 1/n); +} + + + + ``` + + + + + + + ```typescript +function nthRoot(n: number, m: number): number { + return Math.pow(m, 1/n); +} + + + ``` + + + + + + + ```java +public class Main { + public static void main(String[] args) { + int n = 3; + int m = 27; + double result = Math.pow(m, 1.0 / n); + System.out.println(result); + } +} + + + ``` + + + + + +## Time Complexity + +* The iterative approach has a time complexity of $O(1)$. + +## Space Complexity + +* The space complexity is $O(1)$ since we are using only a fixed amount of extra space. \ No newline at end of file