TCS NQT & CAMPUS PLACEMENT
CODING PREPARATION
CHAPTER 1 — NUMBER MANIPULATION
Complete Beginner-Friendly Notes | Print & Study
Section Topic
1 What is Number Manipulation?
2 Core Building Block — The Digit Loop
3 Pattern Recognition Guide
4 Core Tricks & Quick Reference
5 Step-by-Step Thought Process
6 Common Mistakes to Avoid
7 All Subtopics with Theory + Explained Code + Problems
8 Key Algorithms Summary
9 Code Templates for the Exam
10 TCS NQT Style Exam Problems
11 Quick Reference Card
SECTION 1 — WHAT IS NUMBER MANIPULATION?
Number Manipulation means working with the individual digits of a number — breaking it apart, doing math on
each digit, and sometimes rebuilding a new number. It is the most common chapter in TCS NQT and almost every
placement exam.
Every problem in this chapter uses just four simple ideas:
• The % (modulo) operator — gives the remainder after division
• The / (integer division) operator — divides and drops the decimal part
• Loops (while or for) — to repeat steps for every digit
• Basic number rules (prime, factorial, GCD, etc.)
Example — what does 1234 look like to a computer?
Operation Result & Meaning
1234 % 10 4 (last digit)
1234 / 10 123 (number without last digit)
123 % 10 3 (new last digit)
123 / 10 12 (drop another digit)
12 % 10 2
12 / 10 1
1 % 10 1
1 / 10 0 (loop ends here)
NOTE: Using % 10 and / 10 repeatedly is HOW we read every digit of a number one by one. This is the
foundation of ALL number problems.
SECTION 2 — CORE BUILDING BLOCK — THE DIGIT LOOP
2.1 The Master While-Loop (Memorise This First!)
#include <iostream>
using namespace std;
int main() {
int n = 1234;
int original = n; // ALWAYS save a copy before the loop changes n
while (n > 0) { // keep going until no digits are left
int digit = n % 10; // % 10 gives the LAST digit
n = n / 10; // / 10 removes the last digit
// --- do something with 'digit' here ---
}
}
NOTE: This while-loop is the BACKBONE of almost every number problem. Master it and you master the whole
chapter.
2.2 Reversing a Number
To reverse 1234 we want 4321. We read digits from the right (4, 3, 2, 1) and build a new number by appending
each digit to the right of what we have so far.
int n = 1234;
int reversed = 0; // start with 0
while (n > 0) {
int digit = n % 10; // get last digit: 4, then 3, then 2, then 1
reversed = reversed * 10 + digit; // shift left and add digit
// Step-by-step: 0*10+4=4 -> 4*10+3=43 -> 43*10+2=432 -> 432*10+1=4321
n = n / 10;
}
// reversed is now 4321
2.3 GCD (Greatest Common Divisor) — Euclidean Algorithm
GCD of two numbers is the biggest number that divides BOTH of them exactly. Example: GCD(12, 8) = 4 because
4 divides both 12 and 8.
The trick: GCD(a, b) = GCD(b, a % b). Keep replacing until b becomes 0. Whatever is left in a is the answer.
int a = 12, b = 8;
while (b != 0) { // keep going while b is not zero
int temp = b; // save b before we change it
b = a % b; // new b = remainder of a divided by b
a = temp; // new a = old b
}
// a is now the GCD (answer: 4)
TIP: LCM(a, b) = (a / GCD(a, b)) * b — always divide FIRST to avoid overflow.
2.4 Prime Number Check
A prime number has exactly 2 divisors: 1 and itself. Examples: 2, 3, 5, 7, 11, 13...
Key insight: we only need to check divisors up to the square root of n. If no number up to sqrt(n) divides n, then n is
prime.
int n = 97;
bool isPrime = true; // assume prime until proven otherwise
if (n < 2) { // 0 and 1 are NOT prime
isPrime = false;
} else {
int i = 2;
while (i * i <= n) { // only check up to sqrt(n)
if (n % i == 0) { // found a divisor — not prime
isPrime = false;
break;
}
i = i + 1;
}
}
// isPrime is true — 97 is prime
TIP: i * i <= n is the same as i <= sqrt(n) but avoids floating point errors. Always prefer i * i <= n.
SECTION 3 — PATTERN RECOGNITION GUIDE
In TCS NQT the problem is given as a PARAGRAPH (story). Read carefully and find the mathematical rule hidden
in the words. Then match it to the table below.
Keyword / Phrase in Problem Problem Type Approach
reverse the digits Number Reversal Extract digits + rebuild
reads the same forwards/backwards Palindrome Compare n with reverse(n)
sum of digits Digit Sum Extract + add each digit
count of digits Digit Count Count turns in while loop
largest / smallest digit Max/Min Digit Track max/min in loop
sum of factorials of digits Strong Number Sum digit factorials == n
sum of cubes / digit^numDigits Armstrong Number Sum(digit^len) == n
square ends with the number Automorphic Number n^2 % 10^digits == n
divisible by its digit sum Harshad Number n % digitSum == 0
sum of proper divisors == n Perfect Number Sum factors (excl n) == n
sum of proper divisors > n Abundant Number Sum factors > n
no divisors except 1 and itself Prime Number Trial division to sqrt(n)
break into prime factors Prime Factorization Divide by primes one by one
all divisors of n Factor Finding Loop i=1 to sqrt(n)
largest common factor / HCF GCD Euclidean algorithm
smallest common multiple LCM LCM = a*b / GCD(a,b)
a, a+d, a+2d ... Arithmetic Progression nth term = a + (n-1)*d
a, ar, ar^2 ... Geometric Progression nth term = a * r^(n-1)
1, 1, 2, 3, 5, 8 ... Fibonacci F(n) = F(n-1) + F(n-2)
n! or arrangements Factorial Multiply 1 * 2 * ... * n
SECTION 4 — CORE TRICKS & QUICK REFERENCE
Task Trick
Get last digit of n n % 10
Remove last digit of n n / 10
Get last 2 digits of n n % 100
Count digits of n Count how many times you can do n/10 before n becomes 0
Check even / odd n % 2 == 0 (even) n % 2 != 0 (odd)
Reverse check (palindrome) reverse(n) == original_n
Sum of AP (n terms) n * (2*a + (n-1)*d) / 2
Sum of GP (n terms) a * (r^n - 1) / (r - 1) [use a*n if r==1]
GCD of a, b Euclidean: while(b!=0){ temp=b; b=a%b; a=temp; }
LCM of a, b (a / GCD(a,b)) * b
Find all factors of n Loop i = 1 to sqrt(n). If n%i==0 then i and n/i are both factors
Prime factorization Divide by 2 first, then try 3, 5, 7... up to sqrt(n)
Armstrong check Sum of (each digit raised to power = number of digits) == n
Automorphic check n*n % 10^(number of digits in n) == n
Precompute digit factorials Store 0! to 9! in an array — saves recalculating every time
Leap year (y%4==0 && y%100!=0) || y%400==0
Trailing zeros in n! Count 5s: n/5 + n/25 + n/125 + ...
Digital root shortcut If n%9==0 then answer is 9, else answer is n%9
SECTION 5 — STEP-BY-STEP THOUGHT PROCESS
Every time you get a number problem, follow these 8 steps in order:
Step What to Do Example
Read the problem carefully. Find the mathematical rule Example: 'number whose digits sum divides it' =
1. READ hidden in the paragraph. Harshad number
Match keywords from the problem to the pattern table in
2. CLASSIFY Section 3. Example: 'sum of factorials of digits' = Strong number
3. BREAK Decide what operations on digits you need: extract? Armstrong: extract each digit, raise to power, sum
DOWN sum? compare? count? them up
4. EDGE What if n=0? n=1? Negative? Single digit? Handle these
CASES first. 0 and 1 are neither prime nor composite
5. WRITE
LOOP Write the digit extraction while-loop as the main structure. while(n > 0) { digit = n%10; n = n/10; }
6. COMPUTE Do the required calculation inside the loop on each digit. For sum of digits: sum = sum + digit
After the loop, compare the result with the original
7. COMPARE number if needed. If sum == original then YES, else NO
Print exactly what the problem asks: YES/NO, a count, a
8. OUTPUT series, or a value. cout << (sum == orig ? "YES" : "NO");
SECTION 6 — COMMON MISTAKES TO AVOID
COMMON MISTAKE: Not saving the original number — You modify n inside the loop (n = n/10) so at the end n
becomes 0. If you need to compare later, you must save a copy: int original = n; BEFORE the loop.
COMMON MISTAKE: Using float to count digits — log10(0) is undefined and causes a crash. Always handle
n==0 separately. Better: just count in the while-loop (count++ for each step).
COMMON MISTAKE: Integer overflow in factorial — int can only hold up to about 2 billion. 13! is already bigger
than that. Use long long for any factorial calculation. long long is safe up to n=20.
COMMON MISTAKE: Wrong prime check for small numbers — 0 and 1 are NOT prime. Your isPrime function
MUST start with: if (n < 2) return false;
COMMON MISTAKE: Checking factors all the way to n — Checking i = 1 to n is very slow (O(n)). Only check i = 1
to sqrt(n). This is O(sqrt n) — much faster.
COMMON MISTAKE: Forgetting the second factor — When you find that i divides n, BOTH i and n/i are factors.
Always add both (but skip if i==n/i).
COMMON MISTAKE: Armstrong: using power 3 always — The power is the NUMBER OF DIGITS in n, not
always 3. 153 has 3 digits so power=3. 9474 has 4 digits so power=4.
COMMON MISTAKE: LCM overflow — a * b can overflow if both are large. Always write: (a / gcd(a,b)) * b —
divide first, then multiply.
COMMON MISTAKE: Automorphic: using % 100 always — Use 10^(number of digits in n) not just 100. For 5 (1
digit) use %10. For 25 (2 digits) use %100.
COMMON MISTAKE: GP sum formula when r=1 — Formula a*(r^n-1)/(r-1) divides by zero when r=1. Always
check: if r==1, sum = a*n.
COMMON MISTAKE: Comparing reversed string instead of number — Comparing reversed number (integer) is
faster and simpler than converting to string. Prefer integer reversal.
SECTION 7 — ALL SUBTOPICS — THEORY + EXPLAINED CODE +
PROBLEMS
7.1 Reverse a Number
We read digits from right to left using % 10, and rebuild the number from left to right. The formula is: reversed =
reversed * 10 + digit
Think of it like writing on a whiteboard: multiply what you have by 10 to shift it left, then write the new digit in the
units place.
int n = 1234;
int original = n; // save copy
int reversed = 0;
while (n > 0) {
int digit = n % 10; // pick last digit
reversed = reversed * 10 + digit;
n = n / 10; // drop last digit
}
// reversed = 4321
TIP: Palindrome = reverse(n) equals original n. Use this single idea for all palindrome problems.
Problems
• EASY: Reverse 5678. Answer: 8765
• MEDIUM: Check if 1221 is a palindrome. Answer: YES (reverse = 1221)
• HARD: Find all 4-digit palindromes (1000 to 9999). Loop and check each.
• TCS STYLE: 'A banking system flags a 6-digit transaction ID if it reads the same forwards and backwards.
Print FLAGGED or CLEAR.' → Palindrome check.
7.2 Sum of Digits
Simply extract each digit and add it to a running total. This is used as a building block for Harshad numbers, digital
roots, and more.
int n = 9384;
int sum = 0;
while (n > 0) {
sum = sum + (n % 10); // add last digit to sum
n = n / 10; // remove last digit
}
// sum = 9 + 3 + 8 + 4 = 24
Problems
• EASY: Sum of digits of 9384. Answer: 24
• MEDIUM: Digital root — keep summing digits until you get a single digit. Shortcut: if n%9==0 then answer=9,
else answer=n%9.
• HARD: Find all numbers from 1 to N where digit sum is divisible by 7.
• TCS STYLE: 'A loyalty program computes a check digit by summing all digits repeatedly until a single digit
remains.' → Digital root.
7.3 Armstrong (Narcissistic) Number
An Armstrong number equals the sum of each of its digits raised to the power equal to the number of digits in the
number.
Example: 153 has 3 digits. 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 (equals itself!)
Example: 9474 has 4 digits. 9^4 + 4^4 + 7^4 + 4^4 = 6561+256+2401+256 = 9474
int n = 153;
int original = n;
// Step 1: count the digits
int numDigits = 0;
int temp = n;
while (temp > 0) {
numDigits = numDigits + 1;
temp = temp / 10;
}
// numDigits = 3
// Step 2: compute sum of (digit ^ numDigits)
int sum = 0;
temp = n;
while (temp > 0) {
int digit = temp % 10; // get last digit
// raise digit to the power numDigits
int power = 1;
for (int i = 0; i < numDigits; i = i + 1) {
power = power * digit; // multiply digit by itself numDigits times
}
sum = sum + power;
temp = temp / 10;
}
if (sum == original) { // ARMSTRONG! }
COMMON MISTAKE: Power = number of digits, NOT always 3!
Problems
• EASY: Is 153 Armstrong? Yes. 1+125+27=153
• MEDIUM: Print all Armstrong numbers from 1 to 9999.
• HARD: Find the smallest 4-digit Armstrong number. Answer: 1634
• TCS STYLE: 'A number is self-validating if sum of each digit raised to the total number of digits equals the
number. Print VALID or INVALID.' → Armstrong check.
7.4 Strong Number
A Strong number equals the sum of the factorials of its digits.
Example: 145 → 1! + 4! + 5! = 1 + 24 + 120 = 145 (equals itself!)
Other strong numbers: 1, 2, 40585
Reminder: factorial means n! = 1 x 2 x 3 x ... x n. Example: 4! = 24.
// Precompute factorials of 0 to 9 and store in array
// (digit can only be 0-9, so we need at most 10 values)
long long fact[10];
fact[0] = 1; // 0! = 1 by definition
fact[1] = 1; // 1! = 1
fact[2] = 2; // 2! = 2
fact[3] = 6; // 3! = 6
fact[4] = 24; // 4! = 24
fact[5] = 120; // 5! = 120
fact[6] = 720;
fact[7] = 5040;
fact[8] = 40320;
fact[9] = 362880;
int n = 145;
int original = n;
long long sum = 0;
while (n > 0) {
int digit = n % 10; // get last digit
sum = sum + fact[digit]; // look up factorial from array
n = n / 10;
}
if (sum == original) { // STRONG NUMBER! }
TIP: Always precompute the factorial array. A digit is 0-9 so you only need 10 values.
Problems
• EASY: Is 145 Strong? Yes. 1+24+120=145
• MEDIUM: Find all Strong numbers from 1 to 100000. Answer: 1, 2, 145, 40585
• TCS STYLE: 'An authentication system marks a code VALID if it equals the sum of factorials of its digits.' →
Strong number check.
7.5 Prime Number Check
A prime number has exactly 2 divisors: 1 and itself. Examples: 2, 3, 5, 7, 11, 13, 17...
To check: try dividing n by every number from 2 to sqrt(n). If any divides evenly, n is NOT prime. If none do, n IS
prime.
Why only up to sqrt(n)? Because if n has a factor bigger than sqrt(n), it must also have a matching factor smaller
than sqrt(n) — so we would have already found it.
int n = 97;
bool isPrime = true;
if (n < 2) { // 0 and 1 are never prime
isPrime = false;
} else {
int i = 2;
while (i * i <= n) { // i*i <= n is same as i <= sqrt(n)
if (n % i == 0) { // i divides n evenly — not prime
isPrime = false;
break; // no need to check further
}
i = i + 1;
}
}
// isPrime = true (97 is prime)
For finding ALL primes up to N, use the Sieve of Eratosthenes (see Section 8).
Problems
• EASY: Is 97 prime? Yes — no number from 2 to 9 divides it.
• MEDIUM: Count all primes from 1 to N.
• HARD: Find all twin prime pairs (p and p+2 both prime) below N.
• TCS STYLE: 'A package is SECURE if its ID is prime, else STANDARD.' → isPrime check.
7.6 GCD and LCM
GCD (Greatest Common Divisor) = largest number that divides both a and b.
LCM (Least Common Multiple) = smallest number that both a and b divide into.
Formula link: LCM(a, b) = (a * b) / GCD(a, b)
// GCD using Euclidean Algorithm
int a = 12, b = 18;
while (b != 0) {
int temp = b; // save b
b = a % b; // remainder of a/b becomes new b
a = temp; // old b becomes new a
}
// a = 6 (GCD of 12 and 18)
// LCM using the GCD result
int gcd = a; // a now holds GCD
int lcm = (12 / gcd) * 18; // divide first to avoid overflow!
// lcm = 36
TIP: Always write (a / GCD) * b, NOT (a * b) / GCD. Division first prevents overflow.
Problems
• EASY: GCD(12,18)=6. LCM(12,18)=36.
• MEDIUM: GCD of an entire array — apply GCD pairwise: g = GCD(g, arr[i]) for each element.
• TCS STYLE: 'Find the largest tile size dividing both A and B (GCD) and the minimum wall length that fits both
tiles (LCM).'
7.7 Fibonacci Sequence
Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ... Each number = sum of the two before it.
F(0)=0, F(1)=1, F(n) = F(n-1) + F(n-2)
Keywords to recognise: 'rabbit population', 'sum of previous two', 'nature spiral'.
// Print first N fibonacci numbers
int n = 10;
long long a = 0; // first term
long long b = 1; // second term
for (int i = 0; i < n; i = i + 1) {
cout << a << ' '; // print current term
long long c = a + b; // next term = sum of previous two
a = b; // shift: a moves to b
b = c; // b moves to new value
}
// Output: 0 1 1 2 3 5 8 13 21 34
TIP: To find the Nth Fibonacci number (0-indexed), run the loop n times and return a.
Problems
• EASY: Print first 10 Fibonacci numbers.
• MEDIUM: Check if a number N is a Fibonacci number. A number n is Fibonacci if 5*n*n+4 or 5*n*n-4 is a
perfect square.
• TCS STYLE: 'A botanist numbers zones. Each zone count = sum of previous two. Zone 1=0, Zone 2=1.
Given zone Z, find the tree count.' → Fibonacci(Z-1).
7.8 Factorial
n! = 1 * 2 * 3 * ... * n. Special case: 0! = 1.
Factorials grow VERY fast. 13! already overflows int (2 billion limit). Always use long long.
int n = 7;
long long result = 1; // start from 1 (not 0, because 0*anything=0)
for (int i = 2; i <= n; i = i + 1) {
result = result * i; // multiply each number from 2 to n
}
// result = 1*2*3*4*5*6*7 = 5040
COMMON MISTAKE: Use long long, not int. int overflows for n > 12. long long safe up to n = 20.
Trailing Zeros in n!
Trailing zeros come from pairs of 2 and 5 in the prime factorization. Since there are always more 2s than 5s, just
count the 5s.
int n = 100;
int count = 0;
while (n >= 5) {
count = count + n / 5; // how many multiples of 5 are in n!
n = n / 5; // now check multiples of 25, 125...
}
// Trailing zeros in 100! = 24
Problems
• EASY: 7! = 5040
• MEDIUM: Count trailing zeros in 100! Answer: 24
• TCS STYLE: 'A professor gives bonus = factorial of correct answers. Given count (max 15), output bonus.' →
Factorial.
7.9 Palindrome Number
A palindrome reads the same forwards and backwards. Simply reverse the number and compare with original.
int n = 1221;
int original = n;
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n = n / 10;
}
if (reversed == original) cout << 'YES'; else cout << 'NO';
7.10 Count Digits / Max Digit / Min Digit
// Count digits
int n = 45678; int count = 0;
while (n > 0) { count = count + 1; n = n / 10; }
// count = 5
// Maximum digit
int n = 45678; int maxD = 0;
while (n > 0) {
int d = n % 10;
if (d > maxD) maxD = d; // update if bigger
n = n / 10;
}
// maxD = 8
7.11 Perfect Number
Sum of ALL proper divisors (all divisors EXCEPT the number itself) equals n.
Example: 28 → divisors are 1,2,4,7,14 → sum=28. Also: 6 (1+2+3=6), 496, 8128.
int n = 28; int sum = 1; // 1 is always a divisor
for (int i = 2; i * i <= n; i = i + 1) {
if (n % i == 0) {
sum = sum + i; // i is a divisor
if (i != n / i) sum = sum + n / i; // n/i is also a divisor
}
}
if (sum == n) cout << 'PERFECT';
7.12 Abundant Number
Sum of proper divisors is GREATER than n. Example: 12 → 1+2+3+4+6=16 > 12.
Same code as Perfect — just change the check to: if (sum > n).
7.13 Harshad Number
A number is Harshad if it is divisible by the sum of its digits. Example: 18 → 1+8=9, 18%9=0.
int n = 18; int temp = n; int digitSum = 0;
while (temp > 0) { digitSum = digitSum + temp % 10; temp = temp / 10; }
if (n % digitSum == 0) cout << 'HARSHAD';
7.14 Automorphic Number
n^2 ends with n. Examples: 5^2=25 ends with 5. 76^2=5776 ends with 76.
int n = 76;
long long sq = (long long)n * n; // = 5776
// Count digits in n
int digits = 0; int temp = n;
while (temp > 0) { digits = digits + 1; temp = temp / 10; }
// Compute 10^digits (the modulus)
long long mod = 1;
for (int i = 0; i < digits; i = i + 1) mod = mod * 10; // mod = 100
if (sq % mod == n) cout << 'AUTOMORPHIC'; // 5776 % 100 = 76 == n
7.15 Prime Factorization
Breaking a number into its prime factors. Example: 360 = 2 x 2 x 2 x 3 x 3 x 5
Method: divide by 2 as many times as possible, then try 3, 5, 7... up to sqrt(n).
int n = 360;
// First, extract all factors of 2
while (n % 2 == 0) {
cout << 2 << ' ';
n = n / 2;
}
// Now try odd numbers from 3 up to sqrt(n)
int i = 3;
while (i * i <= n) {
while (n % i == 0) { // while i still divides n
cout << i << ' ';
n = n / i;
}
i = i + 2; // skip even numbers (already removed 2s)
}
if (n > 2) cout << n; // remaining n is itself a prime factor
// Output: 2 2 2 3 3 5
7.16 Arithmetic Progression (AP)
AP: a, a+d, a+2d, a+3d ... 'a' = first term, 'd' = common difference.
Nth term = a + (n-1)*d. Sum of n terms = n * (2a + (n-1)*d) / 2
7.17 Geometric Progression (GP)
GP: a, ar, ar^2, ar^3 ... 'a' = first term, 'r' = common ratio.
Nth term = a * r^(n-1). Sum of n terms = a * (r^n - 1) / (r - 1)
COMMON MISTAKE: If r = 1, the formula divides by zero! Use sum = a * n when r = 1.
7.18 Leap Year
int y = 2000;
bool isLeap = false;
if (y % 400 == 0) {
isLeap = true; // divisible by 400 → always leap
} else if (y % 100 == 0) {
isLeap = false; // divisible by 100 but not 400 → NOT leap
} else if (y % 4 == 0) {
isLeap = true; // divisible by 4 → leap
}
// 2000 → true (divisible by 400)
// 1900 → false (divisible by 100 but not 400)
// 2024 → true (divisible by 4, not 100)
SECTION 8 — KEY ALGORITHMS SUMMARY
Algorithm Time How It Works
Repeatedly replace (a,b) with (b, a%b) until b becomes 0. Final a is the
Euclidean Algorithm (GCD) O(log min(a,b)) GCD.
Mark all numbers 2..N as prime. For each prime p, mark all multiples of
Sieve of Eratosthenes O(n log log n) p as not-prime. Best method for finding ALL primes up to N at once.
Trial Division (single prime Check if n is divisible by any number from 2 to sqrt(n). If none divide n,
check) O(sqrt n) it is prime.
Binary Exponentiation (Fast To compute base^exp: if exp is odd, multiply result by base; then
Power) O(log n) square base and halve exp. Repeat until exp=0.
O(log10 n) =
O(number of while(n>0){ digit = n%10; n = n/10; } — use for sum, reverse, count,
Digit Extraction Loop digits) max, Armstrong, etc.
Repeatedly sum digits until single digit. Shortcut: if n%9==0 then
Digital Root O(1) with formula root=9, else root=n%9.
Count how many times 5 is a factor: add n/5 + n/25 + n/125 + ... until
Trailing Zeros in n! O(log5 n) term < 1.
Sieve of Eratosthenes — Explained
The sieve is the fastest way to find all prime numbers up to a large number N. The idea: start by assuming all
numbers are prime. Then go through each prime p and cross out all multiples of p (because they are divisible by p
and so not prime). Only the uncrossed numbers survive.
int N = 50;
// Create array: is_prime[i] = true means i is prime
bool is_prime[51];
for (int i = 0; i <= N; i = i + 1) is_prime[i] = true; // assume all prime
is_prime[0] = false; // 0 is not prime
is_prime[1] = false; // 1 is not prime
for (int i = 2; i * i <= N; i = i + 1) {
if (is_prime[i]) { // i is still prime
// cross out all multiples of i starting from i*i
for (int j = i * i; j <= N; j = j + i) {
is_prime[j] = false; // j is divisible by i, so not prime
}
}
}
// is_prime[2]=T, [3]=T, [4]=F, [5]=T, [6]=F, [7]=T ...
SECTION 9 — CODE TEMPLATES FOR THE EXAM
Copy these templates and fill in your logic. Each one covers a major problem type.
Template 1 — Digit Extraction (Base for Most Problems)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int original = n; // ALWAYS save before loop
int result = 0;
while (n > 0) {
int digit = n % 10; // last digit
// === YOUR LOGIC HERE ===
result = result + digit; // example: sum of digits
n = n / 10; // remove last digit
}
cout << result;
return 0;
}
Template 2 — Factor Finding (Perfect / Abundant / Harshad)
int n; cin >> n;
int sum = 1; // 1 is always a proper divisor
for (int i = 2; i * i <= n; i = i + 1) {
if (n % i == 0) { // i divides n evenly
sum = sum + i; // i is a factor
if (i != n / i) sum = sum + n / i; // n/i is also a factor
}
}
// Use sum: if sum==n → PERFECT | if sum>n → ABUNDANT
Template 3 — Prime Sieve (for Multiple Queries)
const int MAXN = 1000001;
bool is_prime[MAXN];
void buildSieve() {
for (int i = 0; i < MAXN; i = i + 1) is_prime[i] = true;
is_prime[0] = false; is_prime[1] = false;
for (int i = 2; i * i < MAXN; i = i + 1) {
if (is_prime[i]) {
for (int j = i * i; j < MAXN; j = j + i)
is_prime[j] = false;
}
}
}
Template 4 — Full Starter Template
#include <iostream>
#include <cmath>
using namespace std;
// GCD function
int gcd(int a, int b) {
while (b != 0) { int t = b; b = a % b; a = t; }
return a;
}
// Prime check function
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i = i + 1)
if (n % i == 0) return false;
return true;
}
// Factorial array (0! to 9!)
long long fact[10] = {1,1,2,6,24,120,720,5040,40320,362880};
int main() {
// YOUR CODE HERE
return 0;
}
SECTION 10 — TCS NQT STYLE EXAM SIMULATION PROBLEMS
These are written exactly like TCS NQT paragraphs. Practice finding the hidden mathematical rule in each
description.
Problem 1 — The Digital Vault
A digital vault opens only when a magic number is entered. A magic number is defined as a number where the sum
of each digit raised to the power equal to the total number of digits equals the number itself. For example, the vault
opened when 407 was entered (4^3 + 0^3 + 7^3 = 64+0+343 = 407). Given T test cases each with a number N,
print OPEN or CLOSED.
TIP: Category: Armstrong Number — power = number of digits. Apply isArmstrong(n).
Problem 2 — The Secret Handshake
Two agents can communicate only when they share a secret key. The key is the largest number that divides both
their ID numbers exactly. If agent A has ID 252 and agent B has ID 105, find the key. Also find the smallest number
that both IDs divide exactly — this is the backup key.
TIP: Category: GCD and LCM. GCD(252,105)=21. LCM=252*105/21=1260.
Problem 3 — The Authenticator
An authenticator device generates OTPs. An OTP is SPECIAL if it equals the sum of the factorials of each of its
digits. The device must display SPECIAL for special OTPs and NORMAL otherwise.
TIP: Category: Strong Number. 1!+4!+5! = 1+24+120 = 145 → SPECIAL. Use precomputed factorial array.
Problem 4 — License Plate System
A city's license plate authority flags plates whose number reads identically forwards and backwards. Given a
number N, output FLAGGED if it satisfies the condition, otherwise CLEAR.
TIP: Category: Palindrome check. Reverse N and compare with original.
Problem 5 — The Prime Classifier
A research lab marks a compound PURE if its numeric ID has no divisors other than 1 and itself. All other
compounds are MIXED. IDs can range from 1 to 10^6. Process multiple queries.
TIP: Category: Prime check. Use Sieve of Eratosthenes up to 10^6 for fast O(1) per query.
Problem 6 — The Tiling Company
A construction company makes tiles in two lengths A cm and B cm. Find the minimum wall length where complete
tiles of both sizes fit with no cutting. Also find the largest tile size that is a whole number divisor of both A and B.
TIP: Category: LCM = minimum wall. GCD = largest common size.
Problem 7 — Fibonacci Forest
A forest ranger tracks tree populations. Each zone count = sum of the two preceding zones. Zone 1 has 0 trees,
Zone 2 has 1 tree. Given zone number Z, find the tree count.
TIP: Category: Fibonacci. Zone Z → F(Z-1) (0-indexed). Compute iteratively.
Problem 8 — The Automorphic Code
A cryptography team uses numbers where the number appears as the last digits of its own square. 5 is valid
because 5^2=25 ends with 5. 76 is valid because 76^2=5776 ends with 76. Given N, print VALID or INVALID.
TIP: Category: Automorphic number. Check: n^2 % 10^(numDigits(n)) == n.
SECTION 11 — QUICK REFERENCE CARD — PRINT THIS PAGE
Number Type Definition How to Check
Palindrome reverse(n) == original rev(n) == n
Armstrong Sum(digit ^ numDigits) == n isArmstrong(n)
Strong Sum(digit!) == n Sum factorials == n
Perfect Sum(proper divisors) == n Sum_div == n
Abundant Sum(proper divisors) > n Sum_div > n
Harshad n divisible by its digit sum n % digitSum == 0
Automorphic n^2 ends with n n^2 % 10^digits == n
Prime Only divisors are 1 and n Trial division to sqrt(n)
Fibonacci F(n) = F(n-1) + F(n-2) 5n^2+4 or 5n^2-4 is perfect square
EXAM DAY REMINDERS
• 1. READ the problem. Find the MATHEMATICAL RULE hidden in the paragraph.
• 2. MATCH to the pattern table — what type of number or series is this?
• 3. SAVE original n before extracting digits: int original = n;
• 4. Handle EDGE CASES: n=0, n=1, negative numbers, single digit.
• 5. For prime problems with many queries → USE SIEVE, not repeated isPrime().
• 6. Use long long for factorials, large products, and power calculations.
• 7. LCM: always divide first → (a / gcd(a,b)) * b to avoid overflow.
• 8. GP sum: check r==1 separately, or formula will divide by zero.
• 9. Track both i and n/i when finding factors — you get two at once.
• 10. Armstrong power = number of digits, not always 3.
Prepared for: TCS NQT | Infosys | Wipro | Capgemini | Accenture Campus Placements