Skip to main content
  1. Problem Solving Solutions/

Program to print prime number pyramid

·1 min
Problem Solving
Mayukh Datta
Mayukh Datta
Table of Contents

I think you’ve already figured it out by looking at the above pattern that the numbers are all prime numbers. It takes number of lines \((n)\) as input and prints exactly \(n(n+1)/2\) prime numbers. For example, if \(n=4\) then we have \(4(4+1)/2 = 10\) prime numbers in the pattern. Each line in the pattern has prime numbers exactly equal to the line number. For example, line 4 has 4 prime numbers, similarly, line 7 has 7 prime numbers.

\[\therefore 1 + 2 + 3 + 4 +…+(n-1)+ n\\ = n(n+1)/2\\ or, \sum_{i=1}^{n} i = n(n+1)/2\]

This follows the triangular number sequence.

C code:

#include<stdio.h> #include<stdbool.h> #include<math.h> bool isPrime(int n);

int main(void){ int n, i, j, p=2, r; printf(“Enter the no. of lines, n: “); scanf("%d”, &n); //rows for(i=1;i<=n;i++){ //no. of primes on each line for(j=i;j>=1;j–){ //if it’s a prime don’t increment it rather print it while(!isPrime(p)){ p++; } printf("%d “, p++); } printf(”\n”); } return 0; }

bool isPrime(int n){ long i; if(n<=1) return false; if(n==2) return true; if(n%2 == 0) return false; //even check

for(i=3; i<=sqrt(n); i+=2){ //increment by 2 to avoid checking odd nos.
    if(n%i == 0){
        return false;
return true;


References: #