💻Code execution
Enable code execution on the model
using Glitch9.AIDevKit.Google.GenerativeAI;
var model = new GenerativeModel(
GeminiModel.Gemini15Pro,
tools: "code_execution");
var response = await model.GenerateContentAsync(
"What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.");
Debug.Log(response.Text);import os
import google.generativeai as genai
genai.configure(api_key=os.environ['API_KEY'])
model = genai.GenerativeModel(
model_name='gemini-1.5-pro',
tools='code_execution')
response = model.generate_content((
'What is the sum of the first 50 prime numbers? '
'Generate and run code for the calculation, and make sure you get all 50.'))
print(response.text)```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int sumOfFirst50Primes = SumOfPrimes(50);
Console.WriteLine($"The sum of the first 50 prime numbers is: {sumOfFirst50Primes}");
}
static bool IsPrime(int n)
{
if (n <= 1)
return false;
for (int i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
return false;
}
return true;
}
static int SumOfPrimes(int n)
{
List<int> primes = new List<int>();
int i = 2;
while (primes.Count < n)
{
if (IsPrime(i))
primes.Add(i);
i++;
}
int sum = 0;
foreach (int prime in primes)
{
sum += prime;
}
return sum;
}
}
```
**Explanation:**
1. **`is_prime(n)` Function:**
- Takes an integer `n` as input.
- Returns `False` for numbers less than or equal to 1 (not prime).
- Iterates from 2 up to the square root of `n`. If `n` is divisible by any
number in this range, it's not prime, and we return `False`.
- If the loop completes without finding a divisor, the number is prime, and
we return `True`.
2. **`sum_of_primes(n)` Function:**
- Takes an integer `n` (number of primes desired) as input.
- Initializes an empty list `primes` to store the prime numbers.
- Starts a loop, iterating through numbers starting from 2.
- For each number `i`, it checks if it's prime using the `is_prime()` function.
- If `i` is prime, it's appended to the `primes` list.
- The loop continues until the `primes` list has `n` prime numbers.
- Finally, it calculates and returns the sum of all the prime numbers in the
`primes` list.
3. **Main Part:**
- Calls `sum_of_primes(50)` to get the sum of the first 50 prime numbers.
- Prints the result.
**Output:**
```
The sum of the first 50 prime numbers is: 5117
```Enable code execution on the request
Use code execution in chat
Code execution versus function calling
Last updated
