素数数组 [英] Array of prime numbers
问题描述
我刚开始让我的手脏的红宝石,想知道是否有人能帮助我这个阵列质数的例子。我有问题了项目欧拉,我想红宝石打印素数的数组。但是,每次我运行程序时,其输出仅仅是0。有人可以在这里提供一些线索。谢谢你在前进。
DEF黄金
X = 13195
数= 0
一个= []
而计数< X
如果count%×== 0
a.push(计数)
a.sort
结束
数+ = 1
结束
把一个
结束
假设你想测试,如果 13195
是一个素数,并且希望一个
来保持一个列表,其中数分为 13195
您需要启动计数
2时,因为包括黄金每一个数字是整除1.您还需要使用 x%的计数
,而不是计数%X
。 x%的计数
由数除以x和给你剩下的(这是正确的检查,对0)。
DEF黄金
X = 13195
数= 2
一个= []
而计数< X
如果x%计数== 0
a.push(计数)
结束
数+ = 1
结束
一个
结束ARR =总理
p ARR#此会打印出它融入13195号列表
arr.size == 0 #true如果数字是一个素数,否则为false
请注意,有很多的优化可以在这个算法做检查,如果一个数是素数 - 也就是你的循环条件可以是:
开方=的Math.sqrt(X)
而计数<开方
您只需要检查到你数的平方根,看它是否是一个素数
I just started getting my hands dirty on ruby and was wondering if someone can help me with this array of primes example. I got the problem off of project Euler, and I want ruby to print an array of prime numbers. However, every time I run the program, it outputs just "0". Can someone shed some light here. Thank you in advance.
def prime
x = 13195
count = 0
a = [ ]
while count < x
if count % x == 0
a.push(count)
a.sort
end
count += 1
end
puts a
end
Assuming you want to test if 13195
is a prime, and you want a
to keep a list of which numbers divide into 13195
You need to start count
at 2, since every number including a prime is divisible by 1. You also need to use x % count
instead of count % x
. x % count
divides x by count and gives you the remainder (which are correctly checking against 0 for).
def prime
x = 13195
count = 2
a = [ ]
while count < x
if x % count == 0
a.push(count)
end
count += 1
end
a
end
arr = prime
p arr #this will print out a list of numbers which fit into 13195
arr.size == 0 #true if number is a prime, false otherwise
Note that there is a lot of optimizations you can do in this algorithm to check if a number is a prime - namely your for loop condition can be:
sqrt = Math.sqrt(x)
while count < sqrt
you only need to check up to the square root of your number to see if it's a prime
这篇关于素数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!