Get sum of numbers within range (from 0 to user input) - ruby

This is the code i am using, its purpose is for the user to enter an integer, the program will then take the sum of all the numbers up to and including the one entered. There is probable an easier way to do this
sum = 0
puts "please enter a number"
counter = gets.chomp.to_i
begin
sum += counter
counter -= 1
end while counter == 0

The issue with your code is in counter == 0 condition in your loop, since it runs only once and then if count is not equal to 0 (in other words, if user's input wasn't 1), it stops. You not only can make this without using loops, you can shorten the whole process:
counter = gets.to_i
sum = (0..counter).inject(:+)
Demo
P.S. As you could have noticed, you can omit .chomp when you are using .to_i.

Yes, use something like this (sum from ActiveSupport):
sum = (counter + 1).times.sum
or without ActiveSupport:
sum = (counter + 1).times.inject(&:+)

num = gets.to_i
sum = num*(num+1)/2

If I understood you correctly, you could try something like this...
puts "Please enter a positive number..."
number = gets.chomp.to_i
puts "Sum of all numbers is: #{ (1..number).inject { |sum, n| sum + n} }"
I'm using enumerable method 'inject' to sum up the total. Learn more about 'inject' method at http://ruby-doc.org/core-2.2.2/Enumerable.html#method-i-inject.
Hope this helps!

As I understand you are trying to sum elements of range. Giving number 3, you want to get sum which is 6.
One way (time consuming) is to use inject or sum. You can try following:
1. [*1..value].sum
2. [*1..value].inject(:+)
The other (recommended), very efficient way is to use this equation:
(value + 1) * (value) / 2

Related

Write a program that adds together all the integers from `1` to `250` (inclusive) and `puts`es the total

How would I do this using ruby and only using a while loop with if, elsif and else only?
sum = 0
i = 1
while i < 251
sum += i
i += 1
end
puts sum
You don’t need a while loop to implement this. But if they want a while loop…
n = 250
while true
puts ( n * (n + 1)) / 2
break
end
Some of the comments have alternatives that are interesting, but keeping this one because it has the flow of control at least pass through the while loop. Not sure if it counts as using a loop if control doesn't even enter the body of the loop.

Ruby prime number sum

I am trying to take the sum of the n first prime numbers. I found a way of showing the first 100, but I don't know how to get rid of 1 and how to make a sum with the numbers. I was thinking about storing them into an array, but I can not figure it out.
num = 1
last = 100
while (num <= last)
condition = true
x = 2
while (x <= num / 2)
if (num % x == 0)
condition = false
break
end
x = x + 1
end
primes = [] # Here
if condition
puts num.to_s
primes << num.to_s # Here
end
num = num + 1
end
puts primes.inject(:+) # Here
Based on what I understood from what you guys are saying I added these lines (the ones commented # Here). It still does not print the sum of them. What I meant with getting rid of 1 is that I know that 1 is not considered a prime number, and I do not get how to make it without 1. Thank you very much guys for your time and answers, and please understand that I am just starting to study this.
If you want to add a list of numbers together you can use the following:
list_of_prime_numbers.inject(0) {|total,prime| total + prime}
This will take the list of numbers, and add them one by one to an accumulator (total) that was injected into the loop (.inject(0)), add it to the current number (prime) and then return the total which then becomes the value of total in the next iteration.
I'm not quite sure what you mean by:
I don't know how to get rid of 1
but if you mean to not use the first number (which is 1 in a list of primes starting from 0)
then you could do:
list_of_prime_numbers[1...list_of_prime_numbers.length].
inject(0) {|total,prime| total + prime}
Which would only get all the numbers except the first up to but not including the length of the array
and as for getting the number into the array you could push it into the array like so:
list_of_prime_numbers << prime_number
You can make use of Prime Enumerable in ruby
require 'prime'
((1..100).select { |number| Prime.prime?(number) }).inject(:+)
OR
Prime.each(100).inject(:+)
Hope this helps.

Using for-loop to add numbers together

If I randomly put in two numbers (first number is smaller), how do I use a for-loop to add all the numbers between and itself?
ex:
first number: 3
second number: 5
the computer should give an answer of '12'.
How do I do that using a for-loop?
In Ruby we seldom use a for loop because it leaves litter behind. Instead, you can very simply do what you want using inject:
(3..5).inject(:+) # => 12
This is using some of the deeper Ruby magic (:+), which is a symbol for the + method and is passed into inject. How it works is a different question and is something you'll need to learn later.
Don't insist on doing something in a language using a particular construct you learned in another language. That will often force non-idiomatic code and will keep you from learning how to do it as other programmers in that language would do it. That creates maintenance issues and makes you less desirable in the workplace.
Simple for loop across the range you defined:
puts "Enter first number: "
first = gets.to_i
puts "Enter second number: "
second = gets.to_i
total = 0
for i in (first..second) do
total += i
end
puts total
Note that if you don't enter a valid number, it will converted to 0. Also this assumes the second number is larger than the first.
In Rails, or in plain-vanilla Ruby with ActiveSupport, you can do something even simpler than a for loop, or than what other people wrote.
(first_num..second_num).sum
This is shorthand for sum in Ruby:
sum = 0
(first_num..second_num).each { |num| sum += num }
first, second = [3,5]
for x in (0..0) do
p (first + second)*(second - first + 1) / 2
end
I know you said for loop, but why not use what Ruby gives you?
> a = 3
> b = 5
> a.upto(b).inject(0) {|m,o| m += o}
=> 12
If you insist on a for loop...
> m = 0
=> 0
> for i in 3..5
* m += i
* end
=> 3..5
> m
=> 12
Since Ruby 2.4 you directly call sum on an Enumerable.
For Example [1, 2, 3].sum #=> 6
In Ruby it's very rare to see a for loop. In this instance a more idiomatic method would be upto:
x = 3
y = 5
total = 0
x.upto(y) do |n|
total += n
end
puts total
# => 12
Another method would be to use reduce:
total = x.upto(y).reduce do |sum, n|
sum += n
end
...which can be shortened to this:
total = x.upto(y).reduce(&:+)

how do I start this pseudocode

ok I am lost right now by this assignment and just need some help.
The assignment is Design a program that generates the sum of numbers.
Given a number (user input) you need an application that will produce a sum of the numbers from 1 to that given number I just need some help to start because I am just having to hard of a time and i know it might seem easy but never had any experience to any of this at all.
var input = getUserInput;
var sum;
while (input > 0)
{
sum = sum + input--;
}
print sum;
You can start with something as straightforward as this:
input = getuserInput()
count = 0
sum = 0
while count < input:
count = count + 1
sum = sum + count
return sum
...then enhance it.
INPUT number
VARIABLE sum = 0
FOR VARIABLE n = 1 TO number WITH STEP 1 DO
sum += n
END FOR
PRINT sum
Translated to lua it would look like this:
number = tonumber( io.read() )
sum = 0
for n = 1, number, 1 do
sum = sum + n
end
print(sum)
Translated into python it would look like
Number = int(input("Number:"))
Sum = 0
for n in range(1,Number+1):
Sum += n
print(Sum)
Though the pythonic way would resemble:
number = int(input("Number:"))
print(sum(range(number+1)))
When applying this to any language look out for the following:
Converting the user's input to an integer, by default it will normally be a string i.e "...".
Declare a variable to hold the total (in our case sum) before you try to add a number to it i.e n.
Make sure your for loop goes from 1 to number

The 'upto' method in Ruby

I'm learning Ruby, and there has been a bit of talk about the upto method in the book from which I am learning. I'm confused. What exactly does it do?
Example:
grades = [88,99,73,56,87,64]
sum = 0
0.upto(grades.length - 1) do |loop_index|
sum += grades[loop_index]
end
average = sum/grades.length
puts average
Let's try an explanation:
You define an array
grades = [88,99,73,56,87,64]
and prepare a variable to store the sum:
sum = 0
grades.length is 6 (there are 6 elements in the array), (grades.length - 1) is 5.
with 0.upto(5) you loop from 0 to 5, loop_index will be 0, then 1...
The first element of the array is grades[0] (the index in the array starts with 0).
That's why you have to subtract 1 from the number of elements.
0.upto(grades.length - 1) do |loop_index|
Add the loop_index's value to sum.
sum += grades[loop_index]
end
Now you looped on each element and have the sum of all elements of the array.
You can calculate the average:
average = sum/grades.length
Now you write the result to stdout:
puts average
This was a non-ruby-like syntax. Ruby-like you would do it like this:
grades = [88,99,73,56,87,64]
sum = 0
grades.each do |value|
sum += value
end
average = sum/grades.length
puts average
Addendum based on Marc-Andrés comment:
You may use also inject to avoid to define the initial sum:
grades = [88,99,73,56,87,64]
sum = grades.inject do |sum, value|
sum + value
end
average = sum / grades.length
puts average
Or even shorter:
grades = [88,99,73,56,87,64]
average = grades.inject(:+) / grades.length
puts average
From http://www.ruby-doc.org/docs/ProgrammingRuby/html/ref_c_integer.html#upto:
upto int.upto( anInteger ) {| i | block }
Iterates block, passing in integer values from int up to and
including anInteger.
5.upto(10) { |i| print i, " " }
produces:
5 6 7 8 9 10
Upto executes the block given once for each number from the original number "upto" the argument passed. For example:
1.upto(10) {|x| puts x}
will print out the numbers 1 through 10.
It is just another way to do a loop/iterator in Ruby. It says do this action n times based on i being the first number the the number in parens as the limit.
My example would have been this:
1.upto(5) { |i| puts "Countup: #{i}" }
So what you're actually doing here is saying, I want to count up from 1 to the number 5, that's specifically what this part is saying:
1.upto(5)
The latter part of code (a block) is just outputting the iteration of going through the count from 1 up to 5. This is the output you might expect to see:
Countup: 1
Countup: 2
Countup: 3
Countup: 4
Countup: 5
Note: This can be written is another way if you're using multilines:
1.upto(5) do |i|
puts "Countup: #{i}"
end
Hope this helps.
An alternative that looks more like Ruby to me is
require 'descriptive_statistics'
grades=[88,99,73,56,87,64]
sum = grades.sum
average = grades.mean
sd = grades.standard_deviation
Of course it depends what you're doing.

Resources