Check if the large number formed is divisible by 41 or not
Last Updated :
09 Apr, 2023
Given the first two digits of a large number digit1 and digit2. Also given a number c and the length of the actual large number. The next n-2 digits of the large number are calculated using the formula digit[i] = ( digit[i - 1]*c + digit[i - 2] ) % 10. The task is to check whether the number formed is divisible by 41 or not.
Examples:
Input: digit1 = 1 , digit2 = 2 , c = 1 , n = 3
Output: YES
The number formed is 123
which is divisible by 41
Input: digit1 = 1 , digit2 = 4 , c = 6 , n = 3
Output: NO
A naive approach is to form the number using the given formula. Check if the number formed is divisible by 41 or not using % operator. But since the number is very large, it will not be possible to store such a large number.
Efficient Approach : All the digits are calculated using the given formula and then the associative property of multiplication and addition is used to check if it is divisible by 41 or not. A number is divisible by 41 or not means (number % 41) equals 0 or not.
Let X be the large number thus formed, which can be written as.
X = (digit[0] * 10^n-1) + (digit[1] * 10^n-2) + ... + (digit[n-1] * 10^0)
X = ((((digit[0] * 10 + digit[1]) * 10 + digit[2]) * 10 + digit[3]) ... ) * 10 + digit[n-1]
X % 41 = ((((((((digit[0] * 10 + digit[1]) % 41) * 10 + digit[2]) % 41) * 10 + digit[3]) % 41) ... ) * 10 + digit[n-1]) % 41
Hence after all the digits are calculated, below algorithm is followed:
- Initialize the first digit to ans.
- Iterate for all n-1 digits.
- Compute ans at every ith step by (ans * 10 + digit[i]) % 41 using associative property.
- Check for the final value of ans if it divisible by 41 or not.
Below is the implementation of the above approach.
C++
// C++ program to check a large number
// divisible by 41 or not
#include <bits/stdc++.h>
using namespace std;
// Check if a number is divisible by 41 or not
bool DivisibleBy41(int first, int second, int c, int n)
{
// array to store all the digits
int digit[n];
// base values
digit[0] = first;
digit[1] = second;
// calculate remaining digits
for (int i = 2; i < n; i++)
digit[i] = (digit[i - 1] * c + digit[i - 2]) % 10;
// calculate answer
int ans = digit[0];
for (int i = 1; i < n; i++)
ans = (ans * 10 + digit[i]) % 41;
// check for divisibility
if (ans % 41 == 0)
return true;
else
return false;
}
// Driver Code
int main()
{
int first = 1, second = 2, c = 1, n = 3;
if (DivisibleBy41(first, second, c, n))
cout << "YES";
else
cout << "NO";
return 0;
}
C
// C program to check a large number
// divisible by 41 or not
#include <stdbool.h>
#include <stdio.h>
// Check if a number is divisible by 41 or not
bool DivisibleBy41(int first, int second, int c, int n)
{
// array to store all the digits
int digit[n];
// base values
digit[0] = first;
digit[1] = second;
// calculate remaining digits
for (int i = 2; i < n; i++)
digit[i] = (digit[i - 1] * c + digit[i - 2]) % 10;
// calculate answer
int ans = digit[0];
for (int i = 1; i < n; i++)
ans = (ans * 10 + digit[i]) % 41;
// check for divisibility
if (ans % 41 == 0)
return true;
else
return false;
}
// Driver Code
int main()
{
int first = 1, second = 2, c = 1, n = 3;
if (DivisibleBy41(first, second, c, n))
printf("YES");
else
printf("NO");
return 0;
}
// This code is contributed by kothavvsaakash.
Java
// Java program to check
// a large number divisible
// by 41 or not
import java.io.*;
class GFG {
// Check if a number is
// divisible by 41 or not
static boolean DivisibleBy41(int first, int second,
int c, int n)
{
// array to store
// all the digits
int digit[] = new int[n];
// base values
digit[0] = first;
digit[1] = second;
// calculate remaining
// digits
for (int i = 2; i < n; i++)
digit[i]
= (digit[i - 1] * c + digit[i - 2]) % 10;
// calculate answer
int ans = digit[0];
for (int i = 1; i < n; i++)
ans = (ans * 10 + digit[i]) % 41;
// check for
// divisibility
if (ans % 41 == 0)
return true;
else
return false;
}
// Driver Code
public static void main(String[] args)
{
int first = 1, second = 2, c = 1, n = 3;
if (DivisibleBy41(first, second, c, n))
System.out.println("YES");
else
System.out.println("NO");
}
}
// This code is contributed
// by akt_mit
Python3
# Python3 program to check
# a large number divisible
# by 41 or not
# Check if a number is
# divisible by 41 or not
def DivisibleBy41(first,
second, c, n):
# array to store
# all the digits
digit = [0] * n
# base values
digit[0] = first
digit[1] = second
# calculate remaining
# digits
for i in range(2, n):
digit[i] = (digit[i - 1] * c +
digit[i - 2]) % 10
# calculate answer
ans = digit[0]
for i in range(1, n):
ans = (ans * 10 + digit[i]) % 41
# check for
# divisibility
if (ans % 41 == 0):
return True
else:
return False
# Driver Code
first = 1
second = 2
c = 1
n = 3
if (DivisibleBy41(first,
second, c, n)):
print("YES")
else:
print("NO")
# This code is contributed
# by Smita
C#
// C# program to check
// a large number divisible
// by 41 or not
using System;
class GFG {
// Check if a number is
// divisible by 41 or not
static bool DivisibleBy41(int first, int second, int c,
int n)
{
// array to store
// all the digits
int[] digit = new int[n];
// base values
digit[0] = first;
digit[1] = second;
// calculate
// remaining
// digits
for (int i = 2; i < n; i++)
digit[i]
= (digit[i - 1] * c + digit[i - 2]) % 10;
// calculate answer
int ans = digit[0];
for (int i = 1; i < n; i++)
ans = (ans * 10 + digit[i]) % 41;
// check for
// divisibility
if (ans % 41 == 0)
return true;
else
return false;
}
// Driver Code
public static void Main()
{
int first = 1, second = 2, c = 1, n = 3;
if (DivisibleBy41(first, second, c, n))
Console.Write("YES");
else
Console.Write("NO");
}
}
// This code is contributed
// by Smita
PHP
<?php
// PHP program to check a
// large number divisible
// by 41 or not
// Check if a number is
// divisible by 41 or not
function DivisibleBy41($first, $second, $c, $n)
{
// array to store
// all the digits
$digit[$n] = range(1, $n);
// base values
$digit[0] = $first;
$digit[1] = $second;
// calculate remaining digits
for ($i = 2; $i < $n; $i++)
$digit[$i] = ($digit[$i - 1] * $c +
$digit[$i - 2]) % 10;
// calculate answer
$ans = $digit[0];
for ($i = 1; $i < $n; $i++)
$ans = ($ans * 10 + $digit[$i]) % 41;
// check for divisibility
if ($ans % 41 == 0)
return true;
else
return false;
}
// Driver Code
$first = 1;
$second = 2;
$c = 1;
$n = 3;
if (DivisibleBy41($first, $second, $c, $n))
echo "YES";
else
echo "NO";
// This code is contributed by Mahadev.
?>
JavaScript
<script>
// Javascript program to check
// a large number divisible
// by 41 or not
// Check if a number is
// divisible by 41 or not
function DivisibleBy41(first, second, c, n)
{
// array to store
// all the digits
let digit = new Array(n).fill(0);
// base values
digit[0] = first;
digit[1] = second;
// calculate remaining
// digits
for (let i = 2; i < n; i++)
digit[i] = (digit[i - 1] * c +
digit[i - 2]) % 10;
// calculate answer
let ans = digit[0];
for (let i = 1; i < n; i++)
ans = (ans * 10 +
digit[i]) % 41;
// check for
// divisibility
if (ans % 41 == 0)
return true;
else
return false;
}
// driver program
let first = 1, second = 2, c = 1, n = 3;
if (DivisibleBy41(first, second, c, n))
document.write("YES");
else
document.write("NO");
// This code is contributed by susmitakundugoaldanga.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach: Alternating Digit Sum approach
- Calculate the first two digits of the large number.
- Calculate the remaining digits of the large number using the given formula: digit[i] = ( digit[i - 1]*c + digit[i - 2] ) % 10. Append each digit to a list of digits.
- Calculate the alternating sum of the digits starting from the rightmost digit: add the rightmost digit to the sum, subtract the next digit from the sum, add the next digit to the sum, and so on, alternating the sign of each term.
- Check if the alternating sum is divisible by 41. If yes, return "YES"; otherwise, return "NO".
C++
#include <iostream>
#include <vector>
using namespace std;
string isDivisibleBy41(int digit1, int digit2, int c, int n)
{
// Calculate the first two digits of the large number
vector<int> digits{ digit1, digit2 };
// Calculate the remaining digits using the given
// formula
for (int i = 2; i < n; i++) {
digits.push_back((digits[i - 1] * c + digits[i - 2])
% 10);
}
// Calculate the alternating sum of the digits starting
// from the rightmost digit
int sum = 0;
int sign = 1;
for (int i = n - 1; i >= 0; i--) {
sum += sign * digits[i];
sign = -sign;
}
// Check if the alternating sum is divisible by 41
if (sum % 41 == 0) {
return "YES";
}
else {
return "NO";
}
}
// Driver's code
int main()
{
int digit1 = 4;
int digit2 = 5;
int c = 3;
int n = 10;
string result = isDivisibleBy41(digit1, digit2, c, n);
cout << result << endl;
return 0;
}
Python3
def is_divisible_by_41(digit1, digit2, c, n):
# Calculate the first two digits of the large number
digits = [digit1, digit2]
# Calculate the remaining digits using the given formula
for i in range(2, n):
digits.append((digits[i-1] * c + digits[i-2]) % 10)
# Calculate the alternating sum of the digits starting from the rightmost digit
sum = 0
sign = 1
for i in range(n-1, -1, -1):
sum += sign * digits[i]
sign = -sign
# Check if the alternating sum is divisible by 41
if sum % 41 == 0:
return "YES"
else:
return "NO"
# Test case 2
digit1 = 1
digit2 = 4
c = 6
n = 3
print(is_divisible_by_41(digit1, digit2, c, n)) # Output: NO
Java
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args)
{
int digit1 = 4;
int digit2 = 5;
int c = 3;
int n = 10;
String result
= isDivisibleBy41(digit1, digit2, c, n);
System.out.println(result); // Output: YES
}
public static String
isDivisibleBy41(int digit1, int digit2, int c, int n)
{
// Calculate the first two digits of the large
// number
List<Integer> digits = new ArrayList<>();
digits.add(digit1);
digits.add(digit2);
// Calculate the remaining digits using the given
// formula
for (int i = 2; i < n; i++) {
digits.add(
(digits.get(i - 1) * c + digits.get(i - 2))
% 10);
}
// Calculate the alternating sum of the digits
// starting from the rightmost digit
int sum = 0;
int sign = 1;
for (int i = n - 1; i >= 0; i--) {
sum += sign * digits.get(i);
sign = -sign;
}
// Check if the alternating sum is divisible by 41
if (sum % 41 == 0) {
return "YES";
}
else {
return "NO";
}
}
}
JavaScript
function isDivisibleBy41(digit1, digit2, c, n) {
// Calculate the first two digits of the large number
let digits = [digit1, digit2];
// Calculate the remaining digits using the given formula
for (let i = 2; i < n; i++) {
digits.push((digits[i - 1] * c + digits[i - 2]) % 10);
}
// Calculate the alternating sum of the digits starting from the rightmost digit
let sum = 0;
let sign = 1;
for (let i = n - 1; i >= 0; i--) {
sum += sign * digits[i];
sign = -sign;
}
// Check if the alternating sum is divisible by 41
if (sum % 41 == 0) {
return "YES";
} else {
return "NO";
}
}
// Driver's code
let digit1 = 4;
let digit2 = 5;
let c = 3;
let n = 10;
let result = isDivisibleBy41(digit1, digit2, c, n);
console.log(result);
C#
using System;
using System.Collections.Generic;
class MainClass {
public static string
IsDivisibleBy41(int digit1, int digit2, int c, int n)
{
// Calculate the first two digits
// of the large number
List<int> digits = new List<int>();
digits.Add(digit1);
digits.Add(digit2);
// Calculate the remaining digits
// using the given formula
for (int i = 2; i < n; i++) {
digits.Add((digits[i - 1] * c + digits[i - 2])
% 10);
}
// Calculate the alternating sum of
// the digits starting from the
// rightmost digit
int sum = 0;
int sign = 1;
for (int i = n - 1; i >= 0; i--) {
sum += sign * digits[i];
sign = -sign;
}
// Check if the alternating sum
// is divisible by 41
if (sum % 41 == 0) {
return "YES";
}
else {
return "NO";
}
}
// Driver Code
public static void Main(string[] args)
{
int digit1 = 4;
int digit2 = 5;
int c = 3;
int n = 10;
string result
= IsDivisibleBy41(digit1, digit2, c, n);
Console.WriteLine(result); // Output: YES
}
}
The time complexity of the Alternating Digit Sum approach is O(n), where n is the length of the large number.
The auxiliary space of the approach is also O(n), as we need to store the list of digits.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem