English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I'm having trouble with the equations needed. we have learned the loops so far and i think this problem wants me to use the loops, and it looks like i need if-else as well. Here is the problem.

Write a program that asks the user to supply three positive integers k, m and n, with k being greater than 1. the program should compute the sum of all the integers between m and n that are divisible by k.

I don't know how to tell C that that i only want an integer evenly divisible by another. and then, i'm not quite sure how to get the addition of those integers done.

2007-08-09 09:24:19 · 3 answers · asked by Julia D 3 in Computers & Internet Programming & Design

doh! forgot about modulus, and thanks for giving me another example of how to utilize the remainder. I didn't quite see why I would need it before.

2007-08-09 09:33:57 · update #1

3 answers

int sum = 0;
for (int i=m; i<=n; i++)
if ((i % k) == 0) sum += i;

Use the "modulus" operator ("%"). It's the remainder of the first number, when divided by the second. When this is zero, the first number evenly divides by the second one.

So, for example,
5 % 3 = 2,
6 % 3 = 0,
7 % 3 = 1

And if you don't want to include m or n in the list, change the loop from:
for (int i=m; i<=n; i++)
... to:
for (int i=m+1; i
And make sure m is the smaller of the two numbers. You can swap them if not.

=====================
As an alternative, you don't have to check every single number. You could write:
for (int i=(n-(n%k)); i<=m; i+=k)
if (i >=n) sum += i;

... which starts i off as the biggest multiple of k less than or equal to n, and increments i by k in each loop iteration.

You can get rid of the if statement if you initialize i a little better:
for (int i=((n-1+k)-((n-1)%k)); i<=m; i+=k) sum += i;

2007-08-09 09:29:03 · answer #1 · answered by McFate 7 · 0 0

You must ensure that the loop terminates (so that it doesn't last forever). This is how:

#include

void main()
{
int m,n,k , i ,sum = 0;

cout << "Enter k: ";
cin >> k;
if( k <= 1)
cout << "k must be greater than 1";
else
{
cout << "Enter m: ";
cin >> m;
cout << "Enter n: ";
cin >> n;
if(m > n)
{
m = m + n;
n = m - n;
m = m - n;
}
for(i=m ; i< n; i++)
{
if(i % k == 0)
sum +=i;
}
cout << "Sum is " << sum;
}
}

You have to check if m>n otherwise the loop

if(i = m; i< n; i++)

will never terminate.
We do this by swapping m and n if m>n
This is the classic way of swapping 2 numbers with only 2 variables:

m = m + n;
n = m - n;
m = m - n;

This is a complete program - compile and run this to see for yourself.

2007-08-09 16:44:59 · answer #2 · answered by E.M.Bed 5 · 0 0

if (i % k)
{ i is evenly divided by k }
else
{ there is a remainder after the divide }

2007-08-09 16:33:42 · answer #3 · answered by WiseElder 2 · 0 0

fedest.com, questions and answers