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
Related
Can you please explain to me how this loop works? What is going on after first loop and after second etc.
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
>>> print sum(123)
6
def sum(n):
s = 0
while n:
s += n % 10
n /= 10
return s
Better rewrite this way (easier to understand):
def sum(n):
s = 0 // start with s = 0
while n > 0: // while our number is bigger than 0
s += n % 10 // add the last digit to s, for example 54%10 = 4
n /= 10 // integer division = just removing last digit, for example 54/10 = 5
return s // return the result
n > 0 in Python can be simply written as n
but I think it is bad practice for beginners
so basically, what we are doing in this algorithm is that we are taking one digit at a time from least significant digit of the number and adding that in our s (which is sum variable), and once we have added the least significant digit, we are then removing it and doing the above thing again and again till the numbers remains to be zero, so how do we know the least significant digit, well just take the remainder of the n by dividing it with 10, now how do we remove the last digit(least significant digit) , we just divide it with 10, so here you go, let me know if it is not understandable.
int main()
{
int t;
cin>>t;
cout<<floor(log10(t)+1);
return 0;
}
Output
254
3
I actually tried to search this, I'm sure this basic algorithm is everywhere on internet, CS textbooks etc, but I cannot find the right words to search it.
What I want from this algorithm to do is write "A" and "B" with the limit always increasing by 2. Like I want it to write A 3 times, then B 5 times, then A 7 times, then B 9 times and so on. And I plan to have 100 elements in total.
Like: AAABBBBBAAAAAAABBBBBBBBB...
I only want to use a single "for loop" for the entire 100 elements starting from 1 to 100. And just direct/sort "A" and "B" through "if/else if/ else".
I'm just asking for the basic mathematical algorithm behind it, showing it through any programming language would be better or redirecting me to such topic would also be fine.
You can do something like this:
There might be shorter answers, but I find this one easy to understand.
Basically, you keep a bool variable that will tell you if it's A's turn or Bs. Then we keep a variable switch that will tell us when we should switch between them. times is being updated with the repeated times we need to print the next character.
A_B = true
times = 3 // 3,5,7,9,...
switch = 3 // 3,8,15,24,...
for (i from 1 to 100)
if (A_B)
print 'A'
else
print 'B'
if (i == switch)
times += 2
switch += times
A_B = !A_B
Python:
for n in range(1, 101):
print "BA"[(int(sqrt(n)) % 2)],
The parity of the square roots of the integers follows that pattern. (Think that (n+1)²-n² = 2n+1.)
If you prefer to avoid the square root, it suffices to use an extra variable that represents the integer square root and keep it updated
r= 1
for n in range(1, 101):
if r * r <= n:
r+= 1
print "AB"[r % 2],
Here is the snippet you can test on this page. It is an example for about 500 letters totally, sure you can modify it for 100 letters. It is quite flexible that you can change the constants to produce lot of different strings in the same manner.
var toRepeat = ['A', 'B'];
var result='', j, i=3;
var sum=i;
var counter = 0;
while (sum < 500) {
j = counter % 2;
result = result + toRepeat[j].repeat(i);
sum = sum + i;
i = i + 2;
counter++;
}
document.getElementById('hLetters').innerHTML=result;
console.log(result);
<div id="hLetters"></div>
If you want it to be exactly 500 / 100 letters, just use a substring function to trim off the extra letters from the end.
To get 100 groups of A and B with increasing length of 3, 5, 7 and so on, you can run this Python code:
''.join(('B' if i % 2 else 'A') * (2 * i + 3) for i in range(100))
The output is a string of 10200 characters.
If you want the output to have only 100 characters, you can use:
import math
''.join(('B' if math.ceil(math.sqrt(i)) % 2 else 'A') for i in range(2, 102))
In js you can start with somethink like this :
$res ="";
count2 = 0;
for (i=2;i<100; i = i+2) {
count = 0;
alert(i);
while (count < i ) {
$res = $res.concat(String.fromCharCode(65+count2));
count++;
}
count2++;
}
alert ($res);
Hi I am having problems with the following function in Matlab. Can some please help?
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. Write a function called smallest_multiple that returns a uint64, the smallest positive number that is evenly divisible by all of the numbers from 1 to n where n is a positive integer scalar and is the only input argument of the function. If the result would be greater than what can be represented as a uint64, the function returns 0. (Inspired by Project Euler.)
Below is the code I wrote for the function but it gives error
Feedback: Your function made an error for argument(s) 2
Your solution is _not_ correct.
Help please...
function [answer]=smallest_multiple(n)
limit = 1e10;
N = 20;
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)
Your function looks correct. However the argument you pass is a lowercase n instead of an uppercase N, which you use during your code.
So the correct function (with limit as argument) is
function [answer]=smallest_multiple(N,limit)
for i = N:N:limit
for j = N:-1:1
if mod(i,j) ~= 0
break
end
end
if j == 1
answer = i;
break
end
end
fprintf('The smallest evenly divisible number is %.0d\n',answer)
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
I have a algorithm to randomly select element t in a array with out repeated. This is more detail of algorithm
It can explain as folowing:
Initial a array index u that stores the index of numbers from 1 to k (line 1 to 3)
Set initial of gamma from k and reduce by one for each iteration. The purpose of gamma is for without repeated (line 4,9,10)
Random choose a number t from 1 to N(at the j=1, choose 1 to k, N are nonrepated number), and then put the number to the end of array.
Repate the step 2 to 3
If gamma =0,reset gamma=k
This function will return the t.
For example, I have a array A=[1,2,3,4,5,6,7,8,9], k=9 =size(A), N=12 (From 1 to 9, number select only one time). Now I want to use this algorithm to randomly select number t from array A. This is my code. However, it does not similar the line 6 in the algorithm. Is it right? Let see my code help me
function nonRepeat
k=9;
u=1:k; % initial value of index
N=12
gamma=k;
for j=1:N
index=randi(gamma,1); % use other choosing
t=u(index)
%%swapping
temp=u(t);
u(t)=u(gamma);
u(gamma)=temp;
gamma=gamma-1;
if gamma==0
gamma=k;
end
end
end
I think index=randi(gamma,1); is not right because it says select number t randomly but you select index randomly and assign t=u(index).
See if it works,
k = 9;
u = 1 : k;
N = 12;
gamma = k;
for j = 1 : N
t = randi(gamma,1);
temp = u(t);
u(t) = u(gamma);
u(gamma) = temp;
gamma = gamma - 1;
if gamma == 0
gamma = k;
end
end