You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R函数异常排查:提取100-500间被3整除奇数时错误包含101

Fixing Your R Function: Extracting Odd Numbers Divisible by 3 Between 100 and 500

Hey there! Let's break down why your function is incorrectly including 101 and fix it up with clean, reliable logic.

What's Causing the Error in Your Original Code?

The core issue is your loop's tangled logic that prioritizes adding numbers to the result before filtering for divisibility by 3:

  • You start by initializing s as all odd numbers starting at 101.
  • On the first loop iteration (i=101), any(s==i) is always TRUE (since i comes directly from the s sequence). This immediately adds 101 to your result p before you've checked if it's divisible by 3.
  • The subsequent modifications to s don't reverse this initial mistake, and the overall approach of building arrays with repeated c() calls is inefficient and error-prone for R.

Simplified & Corrected Function

Let's rewrite the function with straightforward, efficient logic. We'll first generate all valid odd numbers, then filter for those divisible by 3:

Test <- function(n) {
  if (n <= 100) {
    stop("n must be greater than 100")
  }
  # Generate all odd numbers from 101 to n
  odd_numbers <- seq(from = 101, to = n, by = 2)
  # Filter to keep only numbers divisible by 3
  result <- odd_numbers[odd_numbers %% 3 == 0]
  return(result)
}

Even More Optimized Version

Since numbers that are both odd and divisible by 3 are spaced 6 apart (e.g., 105 → 111 → 117), we can skip filtering entirely by generating the sequence directly:

Test <- function(n) {
  if (n <= 100) {
    stop("n must be greater than 100")
  }
  # Find the first number >100 that's odd AND divisible by 3 (that's 105)
  start <- 101 + ((3 - (101 %% 3)) %% 3)
  # Return empty vector if no valid numbers exist
  if (start > n) {
    return(c())
  }
  # Generate sequence with step 6 (keeps numbers odd and divisible by 3)
  result <- seq(from = start, to = n, by = 6)
  return(result)
}

Test It Out

Run Test(500) now, and you'll get the correct sequence starting at 105, ending at 495—no incorrect values like 101 included.

内容的提问来源于stack exchange,提问作者Keith Wiley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 10:44:11