Austin Schuh | dace2a6 | 2020-08-18 10:56:48 -0700 | [diff] [blame^] | 1 | /* mpz_root(root, u, nth) -- Set ROOT to floor(U^(1/nth)). |
| 2 | Return an indication if the result is exact. |
| 3 | |
| 4 | Copyright 1999-2003, 2005, 2012 Free Software Foundation, Inc. |
| 5 | |
| 6 | This file is part of the GNU MP Library. |
| 7 | |
| 8 | The GNU MP Library is free software; you can redistribute it and/or modify |
| 9 | it under the terms of either: |
| 10 | |
| 11 | * the GNU Lesser General Public License as published by the Free |
| 12 | Software Foundation; either version 3 of the License, or (at your |
| 13 | option) any later version. |
| 14 | |
| 15 | or |
| 16 | |
| 17 | * the GNU General Public License as published by the Free Software |
| 18 | Foundation; either version 2 of the License, or (at your option) any |
| 19 | later version. |
| 20 | |
| 21 | or both in parallel, as here. |
| 22 | |
| 23 | The GNU MP Library is distributed in the hope that it will be useful, but |
| 24 | WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
| 25 | or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 26 | for more details. |
| 27 | |
| 28 | You should have received copies of the GNU General Public License and the |
| 29 | GNU Lesser General Public License along with the GNU MP Library. If not, |
| 30 | see https://www.gnu.org/licenses/. */ |
| 31 | |
| 32 | #include <stdio.h> /* for NULL */ |
| 33 | #include "gmp-impl.h" |
| 34 | |
| 35 | int |
| 36 | mpz_root (mpz_ptr root, mpz_srcptr u, unsigned long int nth) |
| 37 | { |
| 38 | mp_ptr rootp, up; |
| 39 | mp_size_t us, un, rootn, remn; |
| 40 | TMP_DECL; |
| 41 | |
| 42 | us = SIZ(u); |
| 43 | |
| 44 | /* even roots of negatives provoke an exception */ |
| 45 | if (UNLIKELY (us < 0 && (nth & 1) == 0)) |
| 46 | SQRT_OF_NEGATIVE; |
| 47 | |
| 48 | /* root extraction interpreted as c^(1/nth) means a zeroth root should |
| 49 | provoke a divide by zero, do this even if c==0 */ |
| 50 | if (UNLIKELY (nth == 0)) |
| 51 | DIVIDE_BY_ZERO; |
| 52 | |
| 53 | if (us == 0) |
| 54 | { |
| 55 | if (root != NULL) |
| 56 | SIZ(root) = 0; |
| 57 | return 1; /* exact result */ |
| 58 | } |
| 59 | |
| 60 | un = ABS (us); |
| 61 | rootn = (un - 1) / nth + 1; |
| 62 | |
| 63 | TMP_MARK; |
| 64 | |
| 65 | /* FIXME: Perhaps disallow root == NULL */ |
| 66 | if (root != NULL && u != root) |
| 67 | rootp = MPZ_NEWALLOC (root, rootn); |
| 68 | else |
| 69 | rootp = TMP_ALLOC_LIMBS (rootn); |
| 70 | |
| 71 | up = PTR(u); |
| 72 | |
| 73 | if (nth == 1) |
| 74 | { |
| 75 | MPN_COPY (rootp, up, un); |
| 76 | remn = 0; |
| 77 | } |
| 78 | else |
| 79 | { |
| 80 | remn = mpn_rootrem (rootp, NULL, up, un, (mp_limb_t) nth); |
| 81 | } |
| 82 | |
| 83 | if (root != NULL) |
| 84 | { |
| 85 | SIZ(root) = us >= 0 ? rootn : -rootn; |
| 86 | if (u == root) |
| 87 | MPN_COPY (up, rootp, rootn); |
| 88 | } |
| 89 | |
| 90 | TMP_FREE; |
| 91 | return remn == 0; |
| 92 | } |