
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
Suppose we have a number n and another value k, consider we have an array A with first N natural numbers, we have to find the total number of pairs of elements A[i] and A[j] from A, such that, i < j and their sum is divisible by k.
So, if the input is like n = 10 k = 4, then the output will be 10 because there are 10 pairs whose sum is divisible by 4. [(1,3), (1,7), (2,6), (2,10), (3,5), (3,9), (4,8), (5,7), (6,10), (7,9)]
To solve this, we will follow these steps −
- m := floor of (n / k), r := n mod k
- b := a new map
- for i in range 0 to k - 1, do
- b[i] := m
- for i in range m*k+1 to n, do
- j := i mod k
- b[j] := b[j] + 1
- c := 0
- for i in range 0 to k, do
- i1 := i
- i2 :=(k - i) mod k
- if i1 is same as i2, then
- c := c + b[i] *(b[i]-1)
- otherwise,
- c := c + b[i1] *(b[i2])
- return floor of c/2
Example
Let us see the following implementation to get better understanding −
def solve(n, k): m = n // k r = n % k b = {} for i in range(k) : b[i] = m for i in range(m*k+1, n+1) : j = i % k b[j] = b[j] + 1 c = 0 for i in range(k) : i1 = i i2 = (k - i) % k if i1 == i2 : c = c + b[i] * (b[i]-1) else : c = c + b[i1] * (b[i2]) return c//2 n = 10 k = 4 print(solve(n, k))
Input
4, 27
Output
10
- Related Articles
- Number of pairs from the first N natural numbers whose sum is divisible by K in C++
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- PHP program to find the sum of first n natural numbers that are divisible by a number ‘x’ or a number ‘y’
- Maximize the number of sum pairs which are divisible by K in C++
- Count pairs in array whose sum is divisible by K in C++
- Program to find max number of K-sum pairs in Python
- Sum of first N natural numbers which are divisible by X or Y
- Count pairs of numbers from 1 to N with Product divisible by their Sum in C++
- Check if product of first N natural numbers is divisible by their sum in Python
- Sum of first N natural numbers which are divisible by 2 and 7 in C++
- PHP program to find the sum of the first n natural numbers who are not powers of a specific number ‘k’
- Count of pairs from 1 to a and 1 to b whose sum is divisible by N in C++
- Check if an array can be divided into pairs whose sum is divisible by k in Python
- Program to find maximum sum by removing K numbers from ends in python
- Program to Find K-Largest Sum Pairs in Python

Advertisements