🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Number Logic Programs in C
Primes, powers, Fibonacci, triplets and series, solved with a four-question recipe and tested code.
Number logic programs in C are where loops stop being syntax and start being problem solving. Prime numbers, Fibonacci checks, Pythagorean triplets, powers and series sums all follow the same recipe: choose a loop, decide what changes each round, and decide when to stop. In this lecture of our free C programming course you will write seven of these programs from scratch, trace them by hand and read real gcc output. You will also see the embedded C programming angle, such as detecting integer overflow, which is a daily concern on small microcontrollers. Every program here is original and tested, so you can type it in, run it and compare your output with ours.
What You Will Learn
- How to list prime numbers efficiently by testing divisors only up to the square root
- How to sum squares and print cubes of multiples of three using a stepped loop
- How to compute a power with a loop and detect overflow before it happens
- How to test whether a number is a Fibonacci number
- How to find all Pythagorean triplets below 50 with three nested loops
- How to build series sums using a running term, a running gap and an alternating sign
Prerequisites
You should be comfortable with nested loops, the break and continue statements, functions that return a value, and the digit-peeling programs from the previous lecture. You also need to know the integer types int, unsigned long and unsigned long long and roughly how large each one is, since number logic programs in C often hit those limits.
A Recipe for Number Logic Programs in C
Before typing code, answer four questions on paper. The answers write most of the program for you.
| Question | Prime numbers | Series 1 + 2 + 4 + 7 + 11 + 16 |
|---|---|---|
| What changes every round? | The divisor being tested | The term and the gap between terms |
| What do I keep between rounds? | Nothing, just a yes or no answer | The running sum, the current term and the gap |
| When do I stop? | A divisor divides evenly, or divisor squared exceeds n | After the required number of terms |
| What can go wrong? | Treating 1 as prime | Starting the sum at the wrong value |
Problem solving recipe
Program 1: Prime Numbers From 1 to 99
A prime has exactly two divisors, 1 and itself, so 1 is not prime. To test n, try divisors from 2 upwards and stop as soon as one divides evenly. You do not need to go all the way to n: if a number has a divisor larger than its square root, it also has a matching divisor smaller than the square root, which you would have found already. Writing d * d <= n instead of calling a square-root function keeps everything in integers.
File: primes.c
#include <stdio.h>
static int is_prime(int n)
{
int d;
if (n < 2)
return 0;
for (d = 2; d * d <= n; d++) /* no need to test beyond sqrt(n) */
if (n % d == 0)
return 0;
return 1;
}
int main(void)
{
int n, count = 0;
for (n = 1; n <= 99; n++) {
if (!is_prime(n))
continue;
printf("%3d", n);
if (++count % 10 == 0)
putchar('\n');
}
printf("\n%d primes below 100\n", count);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o primes primes.c
$ ./primes
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97
25 primes below 100There are 25 primes below 100. The helper function uses an early return 0 the moment a divisor is found, and the main loop uses continue to skip composites, which connects back to our first lecture in this chapter. The counter ++count % 10 == 0 prints a newline after every tenth prime so the table stays tidy.
Testing n = 35 and n = 37
| n | Divisors tried (d) | Stops because | Result |
|---|---|---|---|
| 35 | 2, 3, 4, 5 | 35 % 5 == 0 | composite |
| 37 | 2, 3, 4, 5, 6 | 7 * 7 = 49 is greater than 37 | prime |
Programs 2 and 3: Sum of Squares and Cubes of Multiples of Three
Two small exercises share one program. The first adds i * i for every i from 1 to n. The second prints the cube of every multiple of three up to n. Instead of testing i % 3 == 0 on every number, start the loop at 3 and step by 3. That is a tiny optimisation, and it makes the intent obvious.
File: sumsq.c
#include <stdio.h>
int main(void)
{
unsigned n, i;
unsigned long squares = 0;
if (scanf("%u", &n) != 1)
return 1;
for (i = 1; i <= n; i++)
squares += (unsigned long)i * i;
printf("sum of squares 1..%u = %lu\n", n, squares);
printf("cubes of multiples of 3 up to %u:", n);
for (i = 3; i <= n; i += 3) /* jump straight to 3, 6, 9 ... */
printf(" %lu", (unsigned long)i * i * i);
putchar('\n');
return 0;
}$ gcc -std=c11 -Wall -Wextra -o sumsq sumsq.c
$ echo "10" | ./sumsq
sum of squares 1..10 = 385
cubes of multiples of 3 up to 10: 27 216 729
$ echo "4" | ./sumsq
sum of squares 1..4 = 30
cubes of multiples of 3 up to 4: 27For n = 10 the squares add up to 385, and the multiples of three are 3, 6 and 9, whose cubes are 27, 216 and 729. For n = 4 only 3 qualifies. Notice the casts to unsigned long before multiplying. Without them, i * i * i would be computed in unsigned int, which can overflow on large inputs before the result is stored in the wider variable.
Program 4: Power With Overflow Detection
Computing x raised to the power y needs no library. Start with a result of 1 and multiply by x exactly y times. The embedded twist is overflow: when the result no longer fits, unsigned arithmetic silently wraps around and gives a wrong but plausible number. The program therefore checks, before each multiplication, whether the result is already larger than the maximum value divided by x.
File: power.c
#include <stdio.h>
#include <limits.h>
static int power_u64(unsigned x, unsigned y, unsigned long long *out)
{
unsigned long long r = 1;
unsigned i;
for (i = 0; i < y; i++) {
if (x != 0 && r > ULLONG_MAX / x)
return 0; /* next multiply would overflow */
r *= x;
}
*out = r;
return 1;
}
int main(void)
{
unsigned tests[][2] = { {2, 10}, {3, 20}, {10, 19}, {10, 20}, {7, 0} };
unsigned long long value;
int k;
for (k = 0; k < 5; k++) {
if (power_u64(tests[k][0], tests[k][1], &value))
printf("%u ^ %u = %llu\n", tests[k][0], tests[k][1], value);
else
printf("%u ^ %u overflows 64 bits\n", tests[k][0], tests[k][1]);
}
return 0;
}$ gcc -std=c11 -Wall -Wextra -o power power.c
$ ./power
2 ^ 10 = 1024
3 ^ 20 = 3486784401
10 ^ 19 = 10000000000000000000
10 ^ 20 overflows 64 bits
7 ^ 0 = 1| Test | Mathematical value | Program says | Why |
|---|---|---|---|
| 2 ^ 10 | 1024 | 1024 | Fits easily |
| 3 ^ 20 | 3486784401 | 3486784401 | Above 32-bit range but fits in 64 bits |
| 10 ^ 19 | 10000000000000000000 | prints the value | Just below the 64-bit unsigned maximum |
| 10 ^ 20 | 100000000000000000000 | overflows | Needs more than 64 bits |
| 7 ^ 0 | 1 | 1 | The empty product is 1 |
The check r > ULLONG_MAX / x asks “would multiplying by x exceed the limit?” without ever performing the multiplication that would overflow. The test for x != 0 avoids dividing by zero. This pattern, check first and compute second, is standard in safe embedded code.
Program 5: Is It a Fibonacci Number?
Fibonacci numbers start 0, 1, 1, 2, 3, 5, 8 and each is the sum of the two before it. To test a number, generate the sequence until you reach or pass it. If you land exactly on it, it is a Fibonacci number.
File: fib.c
#include <stdio.h>
static int is_fibonacci(unsigned long n)
{
unsigned long a = 0, b = 1;
while (b < n) { /* walk the sequence up to n */
unsigned long next = a + b;
a = b;
b = next;
}
return n == 0 || b == n;
}
int main(void)
{
unsigned long tests[] = { 0, 1, 21, 22, 144, 145, 10946 };
int k;
for (k = 0; k < 7; k++)
printf("%6lu : %s\n", tests[k],
is_fibonacci(tests[k]) ? "fibonacci" : "not fibonacci");
return 0;
}$ gcc -std=c11 -Wall -Wextra -o fib fib.c
$ ./fib
0 : fibonacci
1 : fibonacci
21 : fibonacci
22 : not fibonacci
144 : fibonacci
145 : not fibonacci
10946 : fibonacciWalking the sequence for n = 22
| Step | a | b | b < 22 ? |
|---|---|---|---|
| start | 0 | 1 | yes |
| 1 | 1 | 1 | yes |
| 2 | 1 | 2 | yes |
| 3 | 2 | 3 | yes |
| 4 | 3 | 5 | yes |
| 5 | 5 | 8 | yes |
| 6 | 8 | 13 | yes |
| 7 | 13 | 21 | yes |
| 8 | 21 | 34 | no, and 34 is not 22 |
The walk passes 22 without landing on it, so 22 is reported as not Fibonacci, while 21, 144 and 10946 are. The special case for 0 is needed because the loop condition b < n is false immediately for n = 0 and b is 1. Fibonacci-style growth is used in embedded networking for retry delays, where each wait is the sum of the previous two.
Program 6: Pythagorean Triplets Below 50
A Pythagorean triplet is three positive integers with x < y < z and x squared plus y squared equal to z squared. The direct method tries every combination with three nested loops, starting each inner loop just above the outer one so that the order x < y < z is guaranteed and duplicates never appear.
File: triplets.c
#include <stdio.h>
int main(void)
{
int x, y, z, found = 0;
long checks = 0;
for (x = 1; x < 50; x++)
for (y = x + 1; y < 50; y++)
for (z = y + 1; z < 50; z++) {
checks++;
if (x * x + y * y == z * z) {
printf("(%d, %d, %d)\n", x, y, z);
found++;
}
}
printf("%d triplets found after %ld checks\n", found, checks);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o triplets triplets.c
$ ./triplets
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(7, 24, 25)
(8, 15, 17)
(9, 12, 15)
(9, 40, 41)
(10, 24, 26)
(12, 16, 20)
(12, 35, 37)
(15, 20, 25)
(15, 36, 39)
(16, 30, 34)
(18, 24, 30)
(20, 21, 29)
(21, 28, 35)
(24, 32, 40)
(27, 36, 45)
18 triplets found after 18424 checksEighteen triplets exist below 50, from (3, 4, 5) to (27, 36, 45). The counter shows the brute-force cost: 18424 combinations were checked, exactly the number of ways to pick three distinct values from 49, which is 49 x 48 x 47 divided by 6. You can cut this sharply: use only two loops for x and y, compute x*x + y*y, and check whether the result is a perfect square below 50 squared. That needs about 1176 pairs instead of 18424 checks, a fifteen-fold saving.
Rule to remember
Start with the simple brute-force version, make it correct, and only then optimise. Print a counter like the one above to see exactly what you saved.
Program 7: Series Sums in Number Logic Programs in C
The series questions in this chapter are all built from the same moves. Decide how the next term is produced from the previous one, then add each term to a running sum. Four patterns cover the typical exercises.
| Series | How the next term is made | Technique |
|---|---|---|
| 1 + 2 + 4 + 7 + 11 + 16 | Add a gap that grows by one each time | Keep term and gap variables |
| 1 + 11 + 111 + 1111 | Multiply the previous number by 10 and add 1 | Repunit update |
| x + x^2 + x^3 + x^4 | Multiply the previous term by x | Running power |
| 1/x – 1/x^2 + 1/x^3 – 1/x^4 | Divide by x and flip a sign | Alternating sign variable |
File: series.c
#include <stdio.h>
int main(void)
{
int i;
/* 1 + 2 + 4 + 7 + 11 + 16 : the gap grows by one every term */
long s1 = 0, term = 1, gap = 1;
for (i = 0; i < 6; i++) {
s1 += term;
term += gap;
gap++;
}
/* 1 + 11 + 111 + 1111 : each term is the previous one times 10, plus 1 */
long s2 = 0, rep = 0;
for (i = 0; i < 4; i++) {
rep = rep * 10 + 1;
s2 += rep;
}
/* x + x^2 + x^3 + x^4 for x = 3 */
long s3 = 0, p = 1, x = 3;
for (i = 0; i < 4; i++) {
p *= x;
s3 += p;
}
/* 1/x - 1/x^2 + 1/x^3 - 1/x^4 for x = 2 */
double s4 = 0.0, frac = 1.0, sign = 1.0;
for (i = 0; i < 4; i++) {
frac /= 2.0;
s4 += sign * frac;
sign = -sign;
}
printf("gap series = %ld\n", s1);
printf("repunit series = %ld\n", s2);
printf("powers of 3 = %ld\n", s3);
printf("alternating 1/2 = %.4f\n", s4);
return 0;
}$ gcc -std=c11 -Wall -Wextra -o series series.c
$ ./series
gap series = 41
repunit series = 1234
powers of 3 = 120
alternating 1/2 = 0.3125Check the results by hand. The gap series gives 1 + 2 + 4 + 7 + 11 + 16 = 41. The repunits give 1 + 11 + 111 + 1111 = 1234. With x = 3 the powers give 3 + 9 + 27 + 81 = 120. With x = 2 the alternating series gives 0.5 – 0.25 + 0.125 – 0.0625 = 0.3125. The sign variable flips between 1.0 and -1.0 each round, which handles any alternating series without extra if statements.
Series are not just exam material. Embedded math libraries approximate functions such as sine and exponential with a short series, often called a Taylor series, when the chip has no floating-point hardware.
Common Mistakes in Number Logic Programs in C
| Symptom | Cause | Fix |
|---|---|---|
| 1 reported as prime | No special case for numbers below 2 | Return 0 for n < 2 |
| Huge or negative power results | Overflow of the result type | Use a wider type and check before multiplying |
| Series sum is off by one term | Loop runs one time too many or too few | Trace the first and last term by hand |
| Series prints 0 for 1/x terms | Integer division of 1 by x | Use double constants such as 1.0 |
| Duplicate triplets such as (4, 3, 5) | Inner loops start at 1 instead of above the outer | Start y at x + 1 and z at y + 1 |
| Fibonacci test fails for 0 | Loop condition skips the special case | Handle 0 explicitly |
Best Practices for Number Logic Programs in C
- Write a helper function for each test, such as
is_prime, so you can reuse and test it separately. - Use integer arithmetic where possible. The condition
d * d <= navoids floating point and works on chips without an FPU. - Performance: reduce the work before you speed up the code. Testing divisors to the square root, or two loops instead of three, beats any micro-optimisation.
- Safety: check for overflow before the operation, as in the power program, rather than trying to detect it afterwards.
- Test edge cases: 0, 1, 2, the largest allowed value and a value just above it.
Summary and Key Takeaways
- Number logic programs in C start with a hand-worked example; for primes, test divisors up to the square root and treat numbers below 2 specially.
- Stepped loops, such as starting at 3 and adding 3, express intent and save tests.
- Powers need overflow checks; compare against the maximum divided by the multiplier.
- Fibonacci tests walk the sequence; triplets use ordered nested loops.
- Series sums use a running term, a gap or a sign variable.
Conclusion
Number logic programs in C reward the habit of working one example by hand before touching the keyboard. Every program in this lecture followed the same four questions: what changes, what is kept, when to stop and what can go wrong. Use that recipe on the remaining programming exercises of the chapter, then test yourself with the quiz and interview questions in the final lecture of this set. Keep following this free embedded C course in order, and compile every example.
Frequently Asked Questions
How do I check whether a number is prime in C?
Return 0 for numbers below 2, then try divisors from 2 while d * d is less than or equal to n. If any divisor divides n exactly, the number is not prime.
Why only check divisors up to the square root?
If n has a divisor larger than its square root, it also has a matching smaller one, which the loop would have found earlier.
How do I calculate x to the power y without math.h?
Start a result at 1 and multiply by x in a loop that runs y times. Use an unsigned 64-bit type and check for overflow before each multiplication.
How can I detect integer overflow in C?
For unsigned multiplication, check whether the current result exceeds the maximum value divided by the multiplier before multiplying. Signed overflow is undefined behaviour, so always check first.
How do I test whether a number is a Fibonacci number?
Generate the sequence until the current value is greater than or equal to the number. If it equals the number, it is a Fibonacci number. Treat 0 as a special case.
How many Pythagorean triplets are there below 50?
There are 18, starting with (3, 4, 5) and ending with (27, 36, 45), when you require x < y < z.
How do I write an alternating series in C?
Keep a sign variable that starts at 1.0, multiply each term by it and flip it with sign = -sign after every term.
Why do number logic programs matter in embedded C programming?
They train the skills behind overflow-safe arithmetic, fixed-size loops, lookup logic and series approximations, all common on microcontrollers.
Keep Going With the Free C Course
This free C tutorial builds real problem-solving skill for embedded C programming. Continue to the final lecture for the quiz and interview questions.

2 Comments