Sophie Germain Prime number in C++
Numbers higher than one are known as prime numbers, and they only consist of the number itself plus factor 1. It shows that no number could be divided into these numbers without leaving a residue, excluding 1 and the number itself. For example, 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29 are the first 10 prime numbers. If we choose option 2, elements are 1 and 2, i.e., both the actual number and the first component. Likewise, 11 and 1 are the components if we take 11. After we have a proper understanding of prime numbers, we will discuss the Sophie Germain Prime numbers with several examples.
What is the Sophie Germain Prime numbers?
Problem Statement:
Create a program that prints prime integers that are Sophie Germain Prime Numbers.
Example 1:
Let us take an example to illustrate the Sophie Prime Number in C.
#include<stdio.h>
#include <stdbool.h>
#include <string.h>
bool sieve(int n, bool primeNum[]) {
for (int p = 4; p * p <= n; p++) {
// If prime[p] is not changed, it is a prime
if (primeNum[p] == true) {
// Update all multiples of p
for (int i = p * 4; i <= n; i += p)
primeNum[i] = false;
}
}
}
void SophieGermainPrime(int n) {
bool primeNum[4 * n + 1];
memset(primeNum, true, sizeof(primeNum));
sieve(4 * n + 1, primeNum);
for (int i = 4; i <= n; ++i) {
if (primeNum[i] && primeNum[4 * i + 1])
printf("%d ",i);
}
}
int main() {
int n = 50;
printf("Sophie Germain Primes below 50: ");
SophieGermainPrime(n);
return 0;
}
Output:
On execution, it will produce the following output:
Sophie Germain Primes below 50: 4 5 7 8 9 10 13 14 15 17 18 22 23 27 34 37 39 43
Example 2:
Let us take an example to illustrate the Sophie Prime Number till n in C++.
#include <bits/stdc++.h>
using namespace std;
bool sieve(int n, bool prime[])
{
for (int p = 3; p * p <= n; p++) {
// If prime[p] is not changed, then
// it is a prime
if (prime[p] == true) {
// Update all multiples of p
for (int i = p * 3; i <= n; i += p)
prime[i] = false;
}
}
}
void printSophieGermainNumber(int n)
{
// We have made array till 3*n +1
// so that we can check prime number
// till that and conclude about sophie
// germain prime .
bool prime[3 * n + 1];
memset(prime, true, sizeof(prime));
sieve(3 * n + 1, prime);
for (int i = 3; i <= n; ++i) {
// checking every i whether it is
// sophie germain prime or not.
if (prime[i] && prime[3 * i + 1])
cout << i << " ";
}
}
int main()
{
int n = 25;
printSophieGermainNumber(n);
return 0;
}
Output:
3 4 6 7 10 11 14 19 22
Conclusion:
In conclusion, by entering the value, we can also ascertain whether the given number is a Sophie Germain prime number or not. Thus, the problem of figuring out whether a given number is a prime number of Sophie Germain is solved.