Функции параллелизма Go, такие как горутины и каналы, обеспечивают эффективный и действенный параллелизм в приложениях. BigInt — это встроенная в Go библиотека для выполнения арифметических операций с произвольной точностью над целыми числами.

Учитывая list_data=[1,2,3,4…] . вы должны вернуть список, 0-е место которого хранит сумму значений list_data, 1-е место хранит сумму квадрата значений list_data, 2-е место хранит куб квадрата значений list_data и так далее до 10-го места. Используйте большие данные, golang и параллелизм.

Чтобы решить эту проблему, вы можете использовать комбинацию функций параллелизма Go и его встроенной поддержки больших целых чисел. Этот код запускает горутину для каждого элемента в срезе listData, и каждая горутина вычисляет сумму значений, сумму квадратов значений, куб квадратов значений и т. д. до десятой степени Значение. Результаты отправляются обратно в основную горутину через `result

Вот пример того, как вы можете решить эту проблему в Go:

package main

import (
 "fmt"
 "math/big"
)

func main() {
 listData := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4)}

 result := make([]*big.Int, 11)

 for i := range result {
  result[i] = big.NewInt(0)
 }
 // Create a channel to receive the results from the worker goroutines
 resultChan := make(chan *big.Int, 11)

 // Launch a goroutine for each element in the listData
 for _, value := range listData {
  go func(val *big.Int) {
   // Calculate the sum of the values
   result[0] = new(big.Int).Add(result[0], val)

   // Calculate the sum of the squares of the values
   result[1] = new(big.Int).Add(result[1], new(big.Int).Mul(val, val))

   // Calculate the cube of the square of the values
   result[2] = new(big.Int).Mul(result[1], result[1])

   // Calculate the fourth power of the value
   result[3] = new(big.Int).Mul(result[2], result[2])

   // Calculate the fifth power of the value
   result[4] = new(big.Int).Mul(result[3], result[2])

   // Calculate the sixth power of the value
   result[5] = new(big.Int).Mul(result[4], result[2])

   // Calculate the seventh power of the value
   result[6] = new(big.Int).Mul(result[5], result[2])

   // Calculate the eighth power of the value
   result[7] = new(big.Int).Mul(result[6], result[2])

   // Calculate the ninth power of the value
   result[8] = new(big.Int).Mul(result[7], result[2])

   // Calculate the tenth power of the value
   result[9] = new(big.Int).Mul(result[8], result[2])

   // Send the result back to the main goroutine through the result channel
   resultChan <- result[9]
  }(value)
 }

 // Wait for all the results to be received
 for i := 0; i < len(listData); i++ {
  <-resultChan
 }

 // Print the final result
 fmt.Println(result)
}

если мы не инициализируем. тогда результаты.

Ошибка, которую вы видите, вызвана разыменованием нулевого указателя. Это происходит, когда вы пытаетесь получить доступ к значению указателя, который равен nil или неинициализирован.

В вашем коде слайс result инициализируется как пустой слайс указателей big.Int, но отдельные элементы слайса не инициализируются. В результате, когда вы пытаетесь получить доступ к result[0] в горутине, вы разыменовываете указатель nil, что вызывает ошибку времени выполнения.

Чтобы исправить это, вы можете инициализировать элементы слайса result с помощью big.NewInt(0) перед запуском горутин.

package main

import (
 "fmt"
 "math/big"
)

func main() {
 listData := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4)}

 result := make([]*big.Int, 11)

 // Initialize the elements of the result slice with zero-valued big.Int pointers
 for i := range result {
  result[i] = big.NewInt(0)
 }

 // Create a channel to receive the results from the worker goroutines
 resultChan := make(chan *big.Int, 11)

 // Launch a goroutine for each element in the listData
 for _, value := range listData {
  go func(val *big.Int) {
   // Calculate the sum of the values
   result[0] = new(big.Int).Add(result[0], val)

   // Calculate the sum of the squares of the values
   result[1] = new(big.Int).Add(result[1], new(big.Int).Mul(val, val))

   // Calculate the powers of the value up to the tenth power
   for i := 2; i < 11; i++ {
    result[i] = new(big.Int).Mul(result[i-1], result[1])
   }

   // Send the result back to the main goroutine through the result channel
   resultChan <- result[9]
  }(value)
 }

 // Wait for all the results to be received
 for i := 0; i < len(listData); i++ {
  <-resultChan
 }

 // Print the final result
 fmt.Println(result)
}

В двух словах…

Мы можем расширить эту идею калькулятора, чтобы создать API для больших чисел в качестве проекта. Мы можем добавить каналы для обработки одновременных запросов.