-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParallel computing.cpp
More file actions
74 lines (62 loc) · 1.67 KB
/
Copy pathParallel computing.cpp
File metadata and controls
74 lines (62 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//Sapnil Basnet
//Count Happy Prime Number thourgh reduction clause
#include <iostream>
#include <omp.h>
#include<chrono>
using namespace std;
auto start = chrono::steady_clock::now();
// Function to check if a number is prime
int prime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return 1;
}
if (n % 2 == 0) {
return 0; // Even numbers greater than 2 are not prime
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return 0; // Not a prime number
}
}
return 1; // Prime number
}
// Function to calculate the sum of squares of digits
int square_sum(int n) {
int sum = 0;
#pragma omp parallel for reduction(+:sum)
for (int digit = n % 10; n > 0; n /= 10, digit = n % 10) {
sum += digit * digit;
}
return sum;
}
// Function to check if a number is happy
int happy_num(int n) {
while (n != 1 && n != 4) {
n = square_sum(n);
}
return n == 1;
}
// Function to count happy prime numbers between 1 and n
int total_happy_numbers(int L) {
int count = 0;
#pragma omp parallel for reduction(+:count)
for (int i = 2; i <= L; ++i) {
if (prime(i) && happy_num(i)) {
++count;
}
}
return count;
}
int main() {
int L = 1000000;
int result = total_happy_numbers(L);
std::cout << "The number of happy prime numbers between 1 and " << L << " is: " << result << std::endl;
cout << "\n";
auto end = chrono::steady_clock::now();
auto diff = end - start;
cout << chrono::duration<double, milli>(diff).count() << " ms" << endl;
return 0;
}