如何找到低于给定输入值的所有素数?

如何解决如何找到低于给定输入值的所有素数?

我的任务是在Ruby中查找所有素数(不使用prime方法)

下面是我的逻辑,问题,代码和输出。

我的逻辑:

所有素数只有2个不同的除数。因此,如果我们计算一个数字的除数的数量并且大于2,则它不是质数(除1外,我尚未处理)

因此,我制作了一个数组,并用1至10中的所有数字填充了数组(以后将使用1000),并删除所有具有2个以上除数的数字

问题:

下面的代码似乎没有检查5、7或9。

我的代码(红宝石)

#Create an array that will be your list of prime numbers
primes = [] 
 
#create variables
x = 1
counter = 0
y=1  
 
#fill array with numbers (I'm using 10 rather than 1000 for now)
for x in 1..10 # 1..10 is inclusive in ruby
primes.push(x)  #put x into primes array
end
 
primes.each do |prime_number|  for y in 1..10 do #for each x and each y,do the following
      puts "#{prime_number},#{y}" #puts is print with a new line
      if prime_number % y == 0   #check if element in array divided by numbers 1-10 is mod 0
        counter +=1   #is so increase counter by 1
        if counter > 2
          primes.delete(prime_number)
          counter = 0   #if counter get's above 2 then number cannot be prime. hence remove it from array
        end
      end
    end
end
 
puts primes  #print out primes to check result
sum_of_primes = primes.inject(:+)  #sum of all primes
puts sum_of_primes #print answer

此处输出:

1,1
1,2
1,3
1,4
1,5
1,6
1,7
1,8
1,9
1,10
2,1
2,2
2,3
2,4
2,5
2,6
2,7
2,8
2,9
2,10
4,1
4,2
4,3
4,4
4,5
4,6
4,7
4,8
4,9
4,10
6,1
6,2
6,3
6,4
6,5
6,6
6,7
6,8
6,9
6,10
8,1
8,2
8,3
8,4
8,5
8,6
8,7
8,8
8,9
8,10
10,1
10,2
10,3
10,4
10,5
10,6
10,7
10,8
10,9
10,10
[1,3,5,7,9]
25 

解决方法

TL; DR

您可以重构迭代器以避免显式的循环和计数器。即使您仍在迭代,利用核心方法也可以更快,更容易调试。

出于完整性考虑,我还提供了一个使用标准库中Ruby的Prime模块的示例。这可能是最正确的解决方案,但是使用模块是一种解决方案,至少从实用的角度来看,这种解决方案在很大程度上完全避免了迭代问题。

简化使用迭代器

如果您的问题是关于功课的,那么我的答案可能无法帮助您学习指导老师希望您从课程中学习的内容。其他答案可能会解释为什么您当前的代码无法按预期运行;相反,我将重点介绍利用Ruby的更多核心功能的替代方法。

这里是找到所有给定最大值的正质数的一种方法:

# Use a Range object to check each Integer between 2 and
# (int - 1) to see if there's a remainder. If not,the value
# of i is added to the anonymous array returned by #map. The
# int is prime if there are no elements in the array.
def prime? int 
  (2...int).none? { |i| int.modulo(i).zero? }
end

# Iterate from 2 to the maximum value,using #select to
# return the subset of values passed to the block where the
# return value of #prime? is truthy.
#
# NB: 1 isn't prime,which is why we start from 2. Reference:
# <https://en.wikipedia.org/wiki/Prime_number#Primality_of_one>
def find_primes max_value
  2.upto(max_value).select { |i| prime? i }
end

find_primes 10
#=> [2,3,5,7]

当然还有其他方法可以实现,但是在避免计数器的同时,利用Array#none?Array#select之类的内置迭代器对我来说似乎是一个净赢。您的里程可能会有所不同。

使用标准库

为进一步简化,您可以简单地使用Ruby标准库中的Prime模块。例如,Prime#each返回可枚举的Prime::EratosthenesGenerator。然后,您可以调用Enumerable#to_a将结果转换为数组。例如:

require 'prime'

def primes max_value
  Prime.each(max_value).to_a
end

primes 10
#=> [2,7]

与实施您自己的例程相比,利用核心库和标准库类通常更快(并且可能更少出错),但这对于教育目的而言可能是“一座桥梁”。不过,我将其包括在此处是为了完整性并为将来的访问者提供帮助。

,

下面的代码似乎没有检查5、7或9

那是因为您正在遍历数组时删除了数组中的元素。

作为解决方法,您可以使用reverse_each以相反的顺序遍历数组:

primes = (2..20).to_a

primes.reverse_each do |prime_number|
  counter = 0
  1.upto(20) do |y|
    if prime_number % y == 0
      counter += 1
      primes.delete(prime_number) if counter > 2
    end
  end
end

primes
#=> [2,7,11,13,17,19]

或者您可以使用delete_if,如果该块的求值结果为true,则会就地删除当前元素:

primes = (2..20).to_a

primes.delete_if do |prime_number|
  counter = 0
  (1..20).find do |y|
    counter += 1 if prime_number % y == 0
    counter > 2
  end
end

primes
#=> [2,19]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-