The Wayback Machine - https://web.archive.org/web/20240624014821/https://www.geeksforgeeks.org/expressing-a-fraction-as-a-natural-number-under-modulo-m/
Open In App

Expressing a fraction as a natural number under modulo ‘m’

Last Updated : 23 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers A and B where A is not divisible by B, the task is to express A / B as a natural number modulo m where m = 1000000007. 
Note: This representation is useful where we need to express Probability of an event, Area of Curves and polygons etc.
Examples: 
 

Input: A = 2, B = 6 
Output: 333333336
Input: A = 4, B = 5 
Output: 600000005 
 

 

Approach: We know that, A / B can be written as A * (1 / B) i.e. A * (B ^ -1).
It is known that the modulo(%) operator satisfies the relation: 
 

(a * b) % m = ( (a % m) * (b % m) ) % m

So, we can write: 
 

(b ^ -1) % m = (b ^ m-2) % m (Fermat's little theorem)

Therefore the result will be: 
 

( (A mod m) * ( power(B, m-2) % m) ) % m

Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define m 1000000007
 
// Function to return the GCD of given numbers
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Recursive function to return (x ^ n) % m
ll modexp(ll x, ll n)
{
    if (n == 0) {
        return 1;
    }
    else if (n % 2 == 0) {
        return modexp((x * x) % m, n / 2);
    }
    else {
        return (x * modexp((x * x) % m, (n - 1) / 2) % m);
    }
}
 
// Function to return the fraction modulo mod
ll getFractionModulo(ll a, ll b)
{
    ll c = gcd(a, b);
 
    a = a / c;
    b = b / c;
 
    // (b ^ m-2) % m
    ll d = modexp(b, m - 2);
 
    // Final answer
    ll ans = ((a % m) * (d % m)) % m;
 
    return ans;
}
 
// Driver code
int main()
{
    ll a = 2, b = 6;
 
    cout << getFractionModulo(a, b) << endl;
 
    return 0;
}


Java




// Java implementation of the approach
 
import java.io.*;
 
class GFG {
     
 
 
static long m  = 1000000007;
 
// Function to return the GCD of given numbers
 static long gcd(long a, long b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Recursive function to return (x ^ n) % m
static long modexp(long x, long n)
{
    if (n == 0) {
        return 1;
    }
    else if (n % 2 == 0) {
        return modexp((x * x) % m, n / 2);
    }
    else {
        return (x * modexp((x * x) % m, (n - 1) / 2) % m);
    }
}
 
// Function to return the fraction modulo mod
 static long getFractionModulo(long a, long b)
{
    long c = gcd(a, b);
 
    a = a / c;
    b = b / c;
 
    // (b ^ m-2) % m
    long  d = modexp(b, m - 2);
 
    // Final answer
    long ans = ((a % m) * (d % m)) % m;
 
    return ans;
}
 
// Driver code
 
    public static void main (String[] args) {
        long a = 2, b = 6;
 
    System.out.println(getFractionModulo(a, b));
    }
}
// This code is contributed by inder_verma


Python3




# Python3 implementation of the approach
m = 1000000007
 
# Function to return the GCD
# of given numbers
def gcd(a, b):
 
    if (a == 0):
        return b
    return gcd(b % a, a)
 
# Recursive function to return (x ^ n) % m
def modexp(x, n):
 
    if (n == 0) :
        return 1
     
    elif (n % 2 == 0) :
        return modexp((x * x) % m, n // 2)
     
    else :
        return (x * modexp((x * x) % m,
                           (n - 1) / 2) % m)
 
 
# Function to return the fraction modulo mod
def getFractionModulo(a, b):
 
    c = gcd(a, b)
 
    a = a // c
    b = b // c
 
    # (b ^ m-2) % m
    d = modexp(b, m - 2)
 
    # Final answer
    ans = ((a % m) * (d % m)) % m
 
    return ans
 
# Driver code
if __name__ == "__main__":
 
    a = 2
    b = 6
 
    print ( getFractionModulo(a, b))
 
# This code is contributed by ita_c


C#




//C#  implementation of the approach
 
using System;
 
public class GFG{
     
 
static long m = 1000000007;
 
// Function to return the GCD of given numbers
static long gcd(long a, long b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
 
// Recursive function to return (x ^ n) % m
static long modexp(long x, long n)
{
    if (n == 0) {
        return 1;
    }
    else if (n % 2 == 0) {
        return modexp((x * x) % m, n / 2);
    }
    else {
        return (x * modexp((x * x) % m, (n - 1) / 2) % m);
    }
}
 
// Function to return the fraction modulo mod
static long getFractionModulo(long a, long b)
{
    long c = gcd(a, b);
 
    a = a / c;
    b = b / c;
 
    // (b ^ m-2) % m
    long d = modexp(b, m - 2);
 
    // Final answer
    long ans = ((a % m) * (d % m)) % m;
 
    return ans;
}
 
// Driver code
     
    static public void Main (){
         
        long a = 2, b = 6;
        Console.WriteLine(getFractionModulo(a, b));
    }
}


Javascript




<script>
// javascript implementation of the approach   
var m = 100000007;
 
    // Function to return the GCD of given numbers
    function gcd(a , b) {
        if (a == 0)
            return b;
        return gcd(b % a, a);
    }
 
    // Recursive function to return (x ^ n) % m
    function modexp(x , n) {
        if (n == 0) {
            return 1;
        } else if (n % 2 == 0) {
            return modexp((x * x) % m, n / 2);
        } else {
            return (x * modexp((x * x) % m, (n - 1) / 2) % m);
        }
    }
 
    // Function to return the fraction modulo mod
    function getFractionModulo(a , b) {
        var c = gcd(a, b);
 
        a = a / c;
        b = b / c;
 
        // (b ^ m-2) % m
        var d = modexp(b, m - 2);
 
        // Final answer
        var ans = ((a % m) * (d % m)) % m;
 
        return ans;
    }
 
    // Driver code
 
     
        var a = 2, b = 6;
 
        document.write(getFractionModulo(a, b));
 
// This code is contributed by umadevi9616
</script>


PHP




<?php
// PHP implementation of the approach
 
// Function to return the GCD of
// given numbers
function abc($a, $b)
{
    if ($a == 0)
        return $b;
    return abc($b % $a, $a);
}
 
// Recursive function to return (x ^ n) % m
function modexp($x, $n)
{
    $m = 1000000007;
    if ($n == 0)
    {
        return 1;
    }
    else if ($n % 2 == 0)
    {
        return modexp(($x * $x) % $m, $n / 2);
    }
    else
    {
        return ($x * modexp(($x * $x) % $m,
                        ($n - 1) / 2) % $m);
    }
}
 
// Function to return the fraction
// modulo mod
function getFractionModulo($a, $b)
{
    $m = 1000000007;
    $c = abc($a, $b);
     
    $a = $a / $c;
    $b = $b / $c;
 
    // (b ^ m-2) % m
    $d = modexp($b, $m - 2);
 
    // Final answer
    $ans = (($a % $m) * ($d % $m)) % $m;
 
    return $ans;
}
 
// Driver code
$a = 2;
$b = 6;
 
echo(getFractionModulo($a, $b)) ;
 
// This code is contributed
// by Shivi_Aggarwal
?>


Output

333333336





Time Complexity: O(log(min(a, b) + logm) 
Auxiliary Space: O(log(min(a, b) + logm) 

Approach#2: Using fermat’s little

This approach computes the value of (A/B) % m using Fermat’s Little Theorem to calculate the modular inverse of B.

Algorithm

1. Define a function inverse_modulo(a, m) to compute the inverse of a modulo m using Fermat’s Little Theorem.
2. Define a function fraction_to_natural_modulo(A, B, m) to compute the value of (A/B) % m, where A, B, and m are given integers.
3. Inside the fraction_to_natural_modulo function, calculate the inverse of B modulo m using the inverse_modulo function.
4. Multiply A and the inverse of B modulo m, and take modulo m to get the result.
5. Return the result

C++




#include <iostream>
 
using namespace std;
 
// Function to compute modular exponentiation (a^b % mod)
long long power(long long base, long long exp, long long mod) {
    if (exp == 0) return 1;
    if (exp % 2 == 0) {
        long long half_pow = power(base, exp / 2, mod);
        return (half_pow * half_pow) % mod;
    } else {
        return (base * power(base, exp - 1, mod)) % mod;
    }
}
 
// Function to compute the modular inverse of 'a' modulo 'm' using Fermat's Little Theorem
long long inverse_modulo(long long a, long long m) {
    return power(a, m - 2, m);
}
 
// Function to compute the value of (A/B) % m, where A, B, and m are given integers
long long fraction_to_natural_modulo(long long A, long long B, long long m) {
    // Calculate the modular inverse of B
    long long inverse_B = inverse_modulo(B, m);
    // Compute (A * inverse_B) % m
    long long result = (A * inverse_B) % m;
    return result;
}
 
int main() {
    long long A = 2;
    long long B = 6;
    long long m = 1000000007;
    long long natural_number = fraction_to_natural_modulo(A, B, m);
 
    // Print the result
    cout << natural_number << endl;
    return 0;
}


Java




public class Main {
 
    // Function to compute modular exponentiation (a^b % mod)
    static long power(long base, long exp, long mod) {
        if (exp == 0) return 1;
        if (exp % 2 == 0) {
            long halfPow = power(base, exp / 2, mod);
            return (halfPow * halfPow) % mod;
        } else {
            return (base * power(base, exp - 1, mod)) % mod;
        }
    }
 
    // Function to compute the modular inverse of 'a' modulo 'm' using Fermat's Little Theorem
    static long inverseModulo(long a, long m) {
        return power(a, m - 2, m);
    }
 
    // Function to compute the value of (A/B) % m, where A, B, and m are given integers
    static long fractionToNaturalModulo(long A, long B, long m) {
        // Calculate the modular inverse of B
        long inverseB = inverseModulo(B, m);
        // Compute (A * inverseB) % m
        long result = (A * inverseB) % m;
        return result;
    }
 
    public static void main(String[] args) {
        long A = 2;
        long B = 6;
        long m = 1000000007;
        long naturalNumber = fractionToNaturalModulo(A, B, m);
 
        // Print the result
        System.out.println(naturalNumber);
    }
}
 
// This code is contributed by akshitaguprzj3


Python3




def inverse_modulo(a, m):
    """
    Computes the inverse of a modulo m using Fermat's Little Theorem
    """
    return pow(a, m-2, m)
 
def fraction_to_natural_modulo(A, B, m):
    """
    Computes the value of (A/B) % m, where A, B and m are given integers
    """
    inverse_B = inverse_modulo(B, m)
    result = (A * inverse_B) % m
    return result
 
# Example usage
A = 2
B = 6
m = 1000000007
natural_number = fraction_to_natural_modulo(A, B, m)
print(natural_number)


C#




using System;
 
class Program
{
    // Function to compute modular exponentiation (a^b % mod)
    static long Power(long baseNum, long exp, long mod)
    {
        if (exp == 0) return 1;
        if (exp % 2 == 0)
        {
            long halfPow = Power(baseNum, exp / 2, mod);
            return (halfPow * halfPow) % mod;
        }
        else
        {
            return (baseNum * Power(baseNum, exp - 1, mod)) % mod;
        }
    }
 
    // Function to compute the modular inverse of 'a' modulo 'm' using Fermat's Little Theorem
    static long InverseModulo(long a, long m)
    {
        return Power(a, m - 2, m);
    }
 
    // Function to compute the value of (A/B) % m, where A, B, and m are given integers
    static long FractionToNaturalModulo(long A, long B, long m)
    {
        // Calculate the modular inverse of B
        long inverseB = InverseModulo(B, m);
        // Compute (A * inverseB) % m
        long result = (A * inverseB) % m;
        return result;
    }
 
    static void Main(string[] args)
    {
        long A = 2;
        long B = 6;
        long m = 1000000007;
        long naturalNumber = FractionToNaturalModulo(A, B, m);
 
        // Print the result
        Console.WriteLine(naturalNumber);
    }
}


Javascript




// Function to compute modular exponentiation (a^b % mod)
function power(base, exp, mod) {
    if (exp === 0) return 1;
    if (exp % 2 === 0) {
        let halfPow = power(base, exp / 2, mod);
        return (halfPow * halfPow) % mod;
    } else {
        return (base * power(base, exp - 1, mod)) % mod;
    }
}
 
// Function to compute the modular inverse of 'a' modulo 'm' using the Extended Euclidean Algorithm
function extendedGCD(a, b) {
    if (a === 0) {
        return [b, 0, 1];
    } else {
        let [gcd, x1, y1] = extendedGCD(b % a, a);
        let x = y1 - Math.floor(b / a) * x1;
        let y = x1;
        return [gcd, x, y];
    }
}
 
function inverseModulo(a, m) {
    let [gcd, x, y] = extendedGCD(a, m);
    if (gcd !== 1) {
        // Modular inverse does not exist
        return null;
    } else {
        return (x % m + m) % m;
    }
}
 
// Function to compute the value of (A/B) % m, where A, B, and m are given integers
function fractionToNaturalModulo(A, B, m) {
    // Calculate the modular inverse of B
    let inverseB = inverseModulo(B, m);
    if (inverseB === null) {
        // Modular inverse does not exist
        return null;
    }
    // Compute (A * inverseB) % m
    let result = (A * inverseB) % m;
    return result;
}
 
// Test values
let A = 2;
let B = 6;
let m = 1000000007;
let naturalNumber = fractionToNaturalModulo(A, B, m);
 
// Print the result
console.log(naturalNumber);


Output

333333336





Time complexity:
The time complexity of this code is O(log m) because it uses the pow() function to compute the inverse modulo.

Auxiliary Space:
The space complexity of this code is O(1) because it only stores a few integers in memory.
 



Similar Reads

Find &Delta;X which is added to numerator and denominator both of fraction (a/b) to convert it to another fraction (c/d)
Given a fraction in form of a/b where a &amp; b are positive integers. Find ?X such that when it is added to numerator as well as denominator of given fraction it will result into a new Ir-reducible fraction c/d. Examples: Input : a = 4, b = 10, c = 1, d = 2 Output : ?X = 2 Explanation : (a + ?X)/(b + ?X) = (4 + 2) / (10 + 2) = 6/12 = 1/2 = c/d Inp
4 min read
Find the closest Fraction to given fraction having minimum absolute difference
Given three integers x, y, and n, the task is to find such a pair of integers a, ?b (1?&lt;=?b?&lt;=?n; 0?&lt;=?a) that the value |x/y - a/b| is as minimal as possible, where |x| represents the absolute value of x. Examples: Input: x = 3, y = 7, n = 6Output: 2/5Explanation: a=2 and b=5 and b&lt;=6 then 3/7 - 2/5 = 1/35, which is the minimum differe
8 min read
Find the largest co-prime fraction less than the given fraction
Consider the set of irreducible fractions A = {n/d | n≤d and d ≤ 10000 and gcd(n, d) = 1}. You are given a member of this set and your task is to find the largest fraction in this set less than the given fraction. Note: This is a set and all the members are unique. Examples: Input: n = 1, d = 4Output: {2499, 9997} Explanation: 2499/9997 is the larg
5 min read
Expressing a number as sum of consecutive | Set 2 (Using odd factors)
Given a number n, find the number of ways to represent this number as a sum of 2 or more consecutive natural numbers. Examples : Input : n = 15 Output : 3 15 can be represented as: 1 + 2 + 3 + 4 + 5 4 + 5 + 6 7 + 8 Input :10 Output :2 10 can only be represented as: 1 + 2 + 3 + 4 We have already discussed one approach in below post. Count ways to ex
6 min read
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number
Given a prime number N, the task is to find the closest smaller number than N such that modulo multiplicative inverse of a number under modulo N is equal to the number itself. Examples: Input: N = 7Output: 6Explanation:Modulo multiplicative inverse of all possible natural numbers from 1 to less than N are:Modulo multiplicative inverse of 1 under mo
3 min read
Expressing factorial n as sum of consecutive numbers
Given two numbers N and M. Find the number of ways in which factorial N can be expressed as a sum of two or more consecutive numbers. Print the result modulo M.Examples: Input : N = 3, M = 7 Output : 1 Explanation: 3! can be expressed in one way, i.e. 1 + 2 + 3 = 6. Hence 1 % 7 = 1 Input : N = 4, M = 7 Output : 1 Explanation: 4! can be expressed in
13 min read
Equalizing array using increment under modulo 3
Given an array A containing N non-negative integers. Only following operation can be performed on the array: A[i] = ( A[i] + 1 ) % 3 where A[i] is the element of array A at index i, and performing this operation once costs 1 unit. Find the minimum cost to make all elements equal. Examples : Input : 1 0 3 2 Output : 4 units Explanation: First 3 is c
14 min read
Find Square Root under Modulo p | (When p is product of two primes in the form 4*i + 3)
Given an integer N and an integer P denoting the product of two primes, the task is to find all possible Square Root of N under modulo P if it exists. It is given that P is the product of p1 and p2, where p1 and p2 are prime numbers of the form 4i + 3 where i is any integer. Some examples of such prime numbers are (7, 11, 19, 23, 31). Examples: Inp
15+ min read
Compute n! under modulo p
Given a large number n and a prime p, how to efficiently compute n! % p?Examples : Input: n = 5, p = 13 Output: 3 5! = 120 and 120 % 13 = 3 Input: n = 6, p = 11 Output: 5 6! = 720 and 720 % 11 = 5 A Naive Solution is to first compute n!, then compute n! % p. This solution works fine when the value of n! is small. The value of n! % p is generally ne
15+ min read
Euler's criterion (Check if square root under modulo p exists)
Given a number 'n' and a prime p, find if square root of n under modulo p exists or not. A number x is square root of n under modulo p if (x*x)%p = n%p. Examples : Input: n = 2, p = 5 Output: false There doesn't exist a number x such that (x*x)%5 is 2 Input: n = 2, p = 7 Output: true There exists a number x such that (x*x)%7 is 2. The number is 3.
11 min read
three90RightbarBannerImg