1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

エラトステネスで素因数分解

1
Posted at
prime.rb
puts "xを素因数分解します。"

while true
  print " x > "
  x = gets.to_i #上限
  if x >= 1
    break
  end
end

a = []
for i in 2..x
a << i
end


k = 0 
while k < Math.sqrt(x) 
  i = 1   
  while i < a.length  
    if a[i] % a[k] == 0 && i != k    
      a.delete_at i
    end
    i += 1
  end
  k += 1
end

print x.to_s + " = 1"
for i in 0..(a.length-1)
  count = 0
  while true
    if (x % a[i]) == 0
      x = x / a[i]
      count += 1
      next
    end
    if count > 1
      print " * " + a[i].to_s + "^" + count.to_s
    elsif count == 1
      print " * " + a[i].to_s
    end
    break
  end
end

前回投稿の篩を使っただけ

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?