Check if a large number is divisible by 4 or not
Last Updated :
16 Jul, 2025
Given a number, the task is to check if a number is divisible by 4 or not. The input number may be large and it may not be possible to store even if we use long long int.
Examples:
Input : n = 1124
Output : Yes
Input : n = 1234567589333862
Output : No
Input : n = 363588395960667043875487
Output : No
Using the modulo division operator "%"
This approach directly checks divisibility by 4 using the modulo operator (%
).
- Compute
n % 4
. - If the remainder is
0
, the number is divisible by 4; otherwise, it is not.
C++
#include <iostream>
using namespace std;
int main()
{
// input
long long int n = 1234567589333862;
// finding given number is divisible by 4 or not
if (n % 4 == 0)
{
cout << "Yes";
}
else
{
cout << "No";
}
return 0;
}
C
#include <stdio.h>
int main()
{
// input
long long int n = 1234567589333862;
// finding given number is divisible by 4 or not
if (n % 4 == 0)
{
printf("Yes");
}
else
{
printf("No");
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
public static void main (String[] args) {
// input
long n=123456758933l;
// finding given number is divisible by 4 or not
if (n % 4 == 0)
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
}
Python
# Python code
# To check whether the given number is divisible by 4 or not
#input
n=1234567589333862
# the above input can also be given as n=input() -> taking input from user
# finding given number is divisible by 4 or not
if int(n)%4==0:
print("Yes")
else:
print("No")
C#
using System;
public class GFG{
static public void Main (){
// input
long n=1234567589333862;
// finding given number is divisible by 4 or not
if (n % 4 == 0)
{
Console.Write("Yes");
}
else
{
Console.Write("No");
}
}
}
JavaScript
// JavaScript code for the above approach
// To check whether the given number is divisible by 4 or not
//input
var n = 1234567589333862
// finding given number is divisible by 4 or not
if (n % 4 == 0)
document.write("Yes")
else
document.write("No")
PHP
<?php
$num = 1234567589333862;
// checking if the given number is divisible by 4 or
// not using modulo division operator if the output of
// num%4 is equal to 0 then given number is divisible
// by 4 otherwise not divisible by 4
if ($num % 4 == 0) {
echo "true";
}
else {
echo "false";
}
?>
Time Complexity - O(1)
Auxiliary Space - O(1)
Checking Divisibility of the Last 2 Digits
Since input number may be very large, we cannot use n % 4 to check if a number is divisible by 4 or not, especially in languages like C/C++. The idea is based on following fact.
A number is divisible by 4 if number formed by last two digits of it is divisible by 4. For example, let us consider 76952. Number formed by last two digits = 52. Since 52 is divisible by 4, answer is YES.
How does this work? Let us consider 76952, we can write it as 76952 = 7*10000 + 6*1000 + 9*100 + 5*10 + 2
The proof is based on below observation:
Remainder of 10i divided by 4 is 0 if i greater than or equal to two. Note than 100, 1000, .. etc lead to remainder 0 when divided by 4. So remainder of "7*10000 + 6*1000 + 9*100 + 5*10 + 2" divided by 4 is equivalent to remainder
of following :
0 + 0 + 0 + 5*10 + 2 = 52
Therefore we can say that the whole number is divisible by 4 if 52 is divisible by 4.
C++
// C++ program to find if a number is divisible by
// 4 or not
#include <bits/stdc++.h>
using namespace std;
// Function to find that number divisible by
// 4 or not
bool check(string str)
{
int n = str.length();
// Empty string
if (n == 0)
return false;
// If there is single digit
if (n == 1)
return ((str[0] - '0') % 4 == 0);
// If number formed by last two digits is
// divisible by 4.
int last = str[n - 1] - '0';
int second_last = str[n - 2] - '0';
return ((second_last * 10 + last) % 4 == 0);
}
// Driver code
int main()
{
string str = "76952";
// Function call
check(str) ? cout << "Yes" : cout << "No ";
return 0;
}
C
#include <stdio.h>
#include <string.h>
// Function to find that number divisible by
// 4 or not
int check(char str[]) {
int n = strlen(str);
// Empty string
if (n == 0)
return 0;
// If there is single digit
if (n == 1)
return ((str[0] - '0') % 4 == 0);
// If number formed by last two digits is
// divisible by 4.
int last = str[n - 1] - '0';
int second_last = str[n - 2] - '0';
return ((second_last * 10 + last) % 4 == 0);
}
// Driver code
int main() {
char str[] = "76952";
// Function call
check(str) ? printf("Yes") : printf("No ");
return 0;
}
Java
// Java program to find if a number is
// divisible by 4 or not
import java.util.*;
class IsDivisible
{
// Function to find that number
// is divisible by 4 or not
static boolean check(String str)
{
int n = str.length();
// Empty string
if (n == 0)
return false;
// If there is single digit
if (n == 1)
return ((str.charAt(0) - '0') % 4 == 0);
// If number formed by last two digits is
// divisible by 4.
int last = str.charAt(n - 1) - '0';
int second_last = str.charAt(n - 2) - '0';
return ((second_last * 10 + last) % 4 == 0);
}
// Driver code
public static void main(String[] args)
{
String str = "76952";
// Function call
if (check(str))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python
def check(st):
n = len(st)
if n == 0:
return False
if n == 1:
return (int(st[0]) % 4 == 0)
# If number formed by last two digits is divisible by 4.
last = int(st[n - 1])
second_last = int(st[n - 2])
return ((second_last * 10 + last) % 4 == 0)
# Driver code
st = "76952"
if check(st):
print("Yes")
else:
print("No")
C#
// C# program to find if a number is
// divisible by 4 or not
using System;
class GFG
{
// Function to find that number
// is divisible by 4 or not
static bool check(String str)
{
int n = str.Length;
// Empty string
if (n == 0)
return false;
// If there is single digit
if (n == 1)
return ((str[0] - '0') % 4 == 0);
// If number formed by last two
// digits is divisible by 4.
int last = str[n - 1] - '0';
int second_last = str[n - 2] - '0';
return ((second_last * 10 + last) % 4 == 0);
}
// Driver code
public static void Main()
{
String str = "76952";
// Function call
if (check(str))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is Contributed by nitin mittal.
JavaScript
//Javascript program to check whether a string is divisible by 4 or not
// function to check the divisibility
function check(str)
{
// checking the length for future reference
var n = str.length;
// if it is empty then directly returning false
if( n == 0)
{
return false;
}
if( n == 1)
{
return ((str[0] -'0') % 4 == 0);
}
var lastNumber = str[n-1] -'0';
var lastSecondNUmber = str[n-2] -'0';
return ((lastSecondNUmber * 10 + lastNumber) % 4 == 0);
}
// Driver code
var str="76952";
//checking the value by passing it into the function
// Function call
if(check(str)){
console.log("Yes");
}
else{
console.log("No");
}
PHP
<?php
// PHP program to find if a
// number is divisible by
// 4 or not
// Function to find that
// number divisible by
// 4 or not
function check($str)
{
$n = strlen($str);
// Empty string
if ($n == 0)
return false;
// If there is single digit
if ($n == 1)
return (($str[0] - '0') % 4 == 0);
// If number formed by
// last two digits is
// divisible by 4.
$last = $str[$n - 1] - '0';
$second_last = $str[$n - 2] - '0';
return (($second_last * 10 + $last) % 4 == 0);
}
// Driver code
$str = "76952";
// Function call
$x = check($str)? "Yes" : "No";
echo($x);
// This code is contributed by Ajit.
?>
Time Complexity - O(1)
Auxiliary Space - O(1)
Alternate Implementation - Substring to Integer Conversion
- Use substring function to get the last two characters of the string.
- Convert the string to integer
- Check if it is divisible by 4 or not, using (number%4 == 0).
C++
// C++ program to find if a number is divisible by 4 or not
#include <bits/stdc++.h>
using namespace std;
// Function to find that number divisible by 4 or not
bool check(string str)
{
// Get the length of the string
int n = str.length();
// Empty string
if (n == 0)
return false;
// stoi(string_variable) is used in C++
// to convert string to integer
// If there is single digit
if (n == 1)
return ((stoi(str)) % 4 == 0);
// getting last two characters using substring
str = str.substr(n - 2, 2);
// If number formed by last two digits is divisible by 4.
return ((stoi(str)) % 4 == 0);
}
// Driver code
int main()
{
string str = "76952";
// Function call
check(str) ? cout << "Yes" : cout << "No ";
return 0;
}
C
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to find that number divisible by 4 or not
int check(char *str)
{
// Get the length of the string
int n = strlen(str);
// Empty string
if (n == 0)
return 0;
// If there is single digit
if (n == 1)
return (atoi(str) % 4 == 0);
// Getting last two characters
char lastTwo[3];
strncpy(lastTwo, str + n - 2, 2);
lastTwo[2] = '\0'; // Null-terminate the string
// If number formed by last two digits is divisible by 4.
return (atoi(lastTwo) % 4 == 0);
}
// Driver code
int main()
{
char str[] = "76952";
// Function call
check(str) ? printf("Yes\n") : printf("No\n");
return 0;
}
Java
// Java program to find if a number is divisible by 4 or not
import java.util.*;
public class Main {
// Function to find that number divisible by 4 or not
static boolean check(String str) {
// Empty string
if (str.length() == 0)
return false;
// If there is single digit
if (str.length() == 1)
return (Integer.parseInt(str) % 4 == 0);
// If number formed by last two digits is divisible by 4.
return (Integer.parseInt(str.substring(str.length() - 2)) % 4 == 0);
}
// Driver code
public static void main(String[] args) {
String str = "76952";
// Function call
System.out.println(check(str) ? "Yes" : "No ");
}
}
Python
# Python program to find if a number is divisible by 4 or not
def check(s):
# Empty string
if len(s) == 0:
return False
# If there is single digit
if len(s) == 1:
return int(s) % 4 == 0
# If number formed by last two digits is divisible by 4.
return int(s[-2:]) % 4 == 0
# Driver code
s = "76952"
# Function call
print("Yes" if check(s) else "No ")
C#
// C# program to find if a number is divisible by 4 or not
using System;
class Program {
// Function to find that number divisible by 4 or not
static bool Check(string str) {
// Empty string
if (str.Length == 0)
return false;
// If there is single digit
if (str.Length == 1)
return (int.Parse(str) % 4 == 0);
// If number formed by last two digits is divisible by 4.
return (int.Parse(str.Substring(str.Length - 2)) % 4 == 0);
}
// Driver code
static void Main() {
string str = "76952";
// Function call
Console.WriteLine(Check(str) ? "Yes" : "No ");
}
}
JavaScript
// JavaScript program to find if a number is divisible by 4 or not
function check(s) {
// Empty string
if (s.length === 0) return false;
// If there is single digit
if (s.length === 1) return (parseInt(s) % 4 === 0);
// If number formed by last two digits is divisible by 4.
return (parseInt(s.slice(-2)) % 4 === 0);
}
// Driver code
let str = "76952";
// Function call
console.log(check(str) ? "Yes" : "No ");
PHP
<?php
// PHP program to find if a number is divisible by 4 or not
function check($str) {
// Empty string
if (strlen($str) == 0) return false;
// If there is single digit
if (strlen($str) == 1) return (intval($str) % 4 == 0);
// If number formed by last two digits is divisible by 4.
return (intval(substr($str, -2)) % 4 == 0);
}
// Driver code
$str = "76952";
// Function call
echo check($str) ? "Yes" : "No ";
?>
Time Complexity - O(1)
Auxiliary Space - O(1)
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