Advertisement
LikeRampage

C++ Multithreading Calculate Fibonacci CHATGPT MAKE CODE

Apr 26th, 2024
559
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.60 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4.  
  5. void fibonacci(int n, int& result) {
  6.     if (n <= 1) {
  7.         result = n;
  8.     } else {
  9.         int a, b;
  10.         std::thread t1(fibonacci, n - 1, std::ref(a));
  11.         std::thread t2(fibonacci, n - 2, std::ref(b));
  12.         t1.join();
  13.         t2.join();
  14.         result = a + b;
  15.     }
  16. }
  17.  
  18. int main() {
  19.     int n = 10; // Calculate Fibonacci sequence up to the 10th number
  20.     int result;
  21.    
  22.     fibonacci(n, result);
  23.    
  24.     std::cout << "Fibonacci sequence up to " << n << "th number is: " << result << std::endl;
  25.    
  26.     return 0;
  27. }
Tags: C++
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement