- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Find a positive number M such that gcd(N^M,N&M) is maximum in Python

Suppose we have a number N, we have to find a positive number M such that gcd(N^M, N&M) is as large as possible and m < n. We will also return the largest gcd thus obtained.

So, if the input is like 20, then the output will be 31

To solve this, we will follow these steps −

- if bit_count(n) is same as 0, then
- for i in range 2 to int(square root of (n)) + 1, do
- if n mod i is same as 0, then
- return int(n / i)

- if n mod i is same as 0, then

- for i in range 2 to int(square root of (n)) + 1, do
- otherwise,
- val := 0
- p :=
- dupn := n
- while n is non-zero, do
- if (n AND 1) is same as 0, then
- val := val + p

- p := p * 2
- n := n >> 1

- if (n AND 1) is same as 0, then
- return gcd(val XOR dupn, val AND dupn)

- return 1

## Example

Let us see the following implementation to get better understanding −

from math import gcd, sqrt def bit_count(n): if (n == 0): return 0 else: return (((n & 1) == 0) + bit_count(n >> 1)) def maximum_gcd(n): if (bit_count(n) == 0): for i in range(2, int(sqrt(n)) + 1): if (n % i == 0): return int(n / i) else: val = 0 p = 1 dupn = n while (n): if ((n & 1) == 0): val += p p = p * 2 n = n >> 1 return gcd(val ^ dupn, val & dupn) return 1 n = 20 print(maximum_gcd(n))

## Input

20

## Output

31

- Related Questions & Answers
- Program to find number m such that it has n number of 0s at end in Python
- Count of numbers satisfying m + sum(m) + sum(sum(m)) = N in C++
- Sum of even numbers from n to m regardless if n<m or n>m JavaScript
- Construct PDA for L = {0n1m2(n+m) | m,n >=1}
- Construct DPDA for a(n+m)bmcn n,m≥1 in TOC
- Construct DPDA for anbmc(n+m) n,m≥1 in TOC
- Construct Pushdown automata for L = {0n1m2(n+m) | m,n = 0} in C++
- Construct Pushdown automata for L = {0(n+m)1m2n | m, n = 0} in C++
- Construct Pushdown automata for L = {0m1(n+m)2n | m,n = 0} in C++
- Find the number of sub arrays in the permutation of first N natural numbers such that their median is M in Python
- Construct Turing machine for L = {an bm a(n+m) - n,m≥1} in C++
- Calculate n + nn + nnn + ? + n(m times) in Python
- Construct Pushdown automata for L = {a(2*m)c(4*n)dnbm | m,n = 0} in C++
- Pick maximum sum M elements such that contiguous repetitions do not exceed K in C++
- Find M-th number whose repeated sum of digits of a number is N in C++

Advertisements