Home > Backend Development > C++ > body text

Print prime numbers in reverse order from 1 to N

WBOY
Release: 2023-09-17 12:49:02
forward
872 people have browsed it

Print prime numbers in reverse order from 1 to N

Enter numbers n until prime numbers are calculated and displayed in reverse order

Input : number 30
Output : 29 23 19 17 13 11 7 5 3 2
Copy after login

Algorithm

START
Step 1 -> declare variables as n, I, j, flag to 0 as int
Step 2 -> input number in n
Step 3 -> Loop For from i to n and i>1 and i—
   Step 3.1 ->. Inner loop for from j to i/2 and j>=1 and j—
      Statement If %j==0 && j!=1
         Set flag=0
         Break
      End IF
      Else
         Flag=1
      End Else
   Step 3.2 -> end inner Loop For
Step 4 -> statement IF to check flag=1
   Print i
   End IF
Step 5 -> End outer For
STOP
Copy after login

Example

#include <stdio.h>
int main(int argc, char const *argv[]) {
   int n, i, j, flag=0;
   printf("Enter a number</p><p>");
   scanf("%d", &n);
   for(i=n; i>1; i--) {
      for (j = i/2; j >= 1; j--) {
         if(i%j==0 && j!=1) {
            flag = 0;
            break;
         }
         else
         flag = 1;
      }
      if(flag == 1) {
         printf("%d ", i);
      }
   }
   return 0;
}
Copy after login

Output

If we run the above program, it will generate the following output

Enter a number
30
29 23 19 17 13 11 7 5 3 2
Copy after login

The above is the detailed content of Print prime numbers in reverse order from 1 to N. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template