Back
Close

Rust Sum primes

VonRickroll
1,567 views

The goal today is to write a function that returns the sum of all prime numbers up to a limit. We will do this in two steps: first we're going to write an isPrime function that checks wether or not a number is prime, and then the actual sumPrimes function.

Check if a number is prime

Write an isPrime function that takes an i32 number as parameter and returns true if this number is prime, false if it isn't.

Reminder: A prime number:

  • Can only be divided by 1 and itself
  • Is greater than 1
Write the isPrime function
pub fn is_prime(number: i32) -> bool {
println!("The number is {}", number);
return true;
// For demo purposes:
/*
for i in 2..(number / 2 + 1) {
if number % i == 0 {
return false;
}
}
return number > 1;
*/
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Sum all primes

Write a sumPrimes function to sum all prime numbers up to the parameter limit included. Copy you isPrime function from the last assignment to make use of it

Write the sumPrimes function
pub fn is_prime(number: i32) -> bool {
println!("The number is {}", number);
return true;
// For demo purposes:
/*
for i in 2..(number / 2 + 1) {
if number % i == 0 {
return false;
}
}
return number > 1;
*/
}
pub fn sum_prime(limit: i32) -> i32 {
println!("The limit is {}", limit);
return 0;
// For demo purposes:
/*
let mut sum = 0;
for x in 2..(limit+1) {
if is_prime(x) {
sum += x;
}
}
return sum;
*/
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants