|
|
back to boardC++ - how to value (a*b)%c, when a,b,c are long long? Re: C++ - how to value (a*b)%c, when a,b,c are long long? long long mul(long long a,long long n) { long long ret; if(n==0) return 0; ret=mul(a,n/2); ret=(ret+ret)%mod; if(n%2) ret=(ret+a)%mod; return ret; } Edited by author 24.11.2016 05:02 Re: C++ - how to value (a*b)%c, when a,b,c are long long? Posted by Saikat 5 Oct 2017 06:45 LL product_mod(LL a, LL b, LL mod) { a %= mod; b %= mod; LL result = 0, y = a; while(b) { if(b&1) result = ((result%mod) + y) %mod; y = (y + y)%mod; b = b >> 1; } return result%mod; } This is also known as the Russian peasant method for multiplication. For example, 7x13 13 = (8 + 4 + 1) The product is re-written as 8.7 + 4.7. 1.7 In my code, y keeps track of 7, 2.7. 4.7, 8.7, etc. It gets added to result whenever a bit is set in b. Re: C++ - how to value (a*b)%c, when a,b,c are long long? Posted by ZV 14 May 2021 21:33 long long c = (__int128_t)a*b%md; he he) Edited by author 14.05.2021 21:34 Edited by author 14.05.2021 21:34 |
|
|