Skip to content

Commit

Permalink
feat: degree, odd and even coefs sum functions
Browse files Browse the repository at this point in the history
  • Loading branch information
suleyman-kaya committed Aug 21, 2024
1 parent bdb5c39 commit 24e75ff
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
29 changes: 29 additions & 0 deletions poly/poly.v
Original file line number Diff line number Diff line change
Expand Up @@ -310,3 +310,32 @@ pub fn divide(a []f64, b []f64) ([]f64, []f64) {

return quotient, remainder
}

// degree returns the degree of the given polynomial
// Input: c = [a_0, a_1, ..., a_n]
// Output: Degree of the polynomial as an integer
pub fn degree(c []f64) int {
return c.len - 1
}

// sum_odd_coeffs calculates the sum of the coefficients at odd indices
// Input: c = [a_0, a_1, ..., a_n]
// Output: Sum of the coefficients at odd indices as a floating-point number
pub fn sum_odd_coeffs(c []f64) f64 {
mut sum := 0.0
for i := 1; i < c.len; i += 2 {
sum += c[i]
}
return sum
}

// sum_even_coeffs calculates the sum of the coefficients at even indices
// Input: c = [a_0, a_1, ..., a_n]
// Output: Sum of the coefficients at even indices as a floating-point number
pub fn sum_even_coeffs(c []f64) f64 {
mut sum := 0.0
for i := 0; i < c.len; i += 2 {
sum += c[i]
}
return sum
}
20 changes: 19 additions & 1 deletion poly/poly_test.v
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,23 @@ fn test_divide() {
println('Divide quotient: ${quotient}')
println('Divide remainder: ${remainder}')
assert quotient == [1.0, 1.0]
assert remainder == [] // The empty set indicates that two polynomials divide each other exactly (without remainder).
assert remainder == [] // The empty set indicates that the two polynomials divide each other exactly (without remainder).
}

fn test_degree() {
assert degree([4.0, 5.0, 2.0]) == 2 // Degree should be 2
assert degree([1.0]) == 0 // Degree should be 0 for a single coefficient polynomial
assert degree([]) == -1 // Degree should be -1 for an empty coefficient array
}

fn test_sum_odd_coeffs() {
assert sum_odd_coeffs([4.0, 5.0, 2.0]) == 5.0 // 5 is at an odd index
assert sum_odd_coeffs([7.0, 456.0, 21.0, 87.0]) == 543.0 // 456 and 87 are at odd indices
assert sum_odd_coeffs([]) == 0.0 // The sum should be 0 for an empty coefficient array
}

fn test_sum_even_coeffs() {
assert sum_even_coeffs([4.0, 5.0, 2.0]) == 6.0 // 4.0 and 2 are at even indices
assert sum_even_coeffs([7.0, 456.0, 21.0, 87.0]) == 28.0 // 7 and 21 are at even indices
assert sum_even_coeffs([]) == 0 // The sum should be 0 for an empty coefficient array
}

0 comments on commit 24e75ff

Please sign in to comment.