C for/while loop not summing - c

for (i = 0; i < n; i++)
{
x[i] = (float) (i * step);
k = 5;
sum = 0;
while(k > 0)
{
sum = sum + (1/k) * sin((k*PI*x[i])/5);
k = k - 2;
}
y1[i] = (4/PI)*sum;
y2[i] = 0*(4/PI)*sin((PI*x[i])/5);
}
When debugging for each value of k other than 1 the sum shows as being equal to 0, am I implementing the loop correctly?
EDIT 1:
int k;
double sum;

Since both 1 and k are ints -- 1/k is integer division, its always going to be 0 if k > 1. Therefore nothing is added to sum. You want 1/k to perform floating point division. Try 1.0 / k instead of 1/k.

1/k will give 0. Since it is Integer Division.
You will have to give 1.0/k or 1/(float)k

Related

How to get the result 2^100 * 3^3 in modulo 1000000007

I have a question, how to get a result of (2^100)*(3^5) in modulo 10^9 + 7? The program will ask the user to input the power (2^a) and 3^b, after that, the output will show the result of 2^a * 3^b.
I tried to convert all the big numbers into modulo, and times the modulo. But, it doesnt work for 2*100 * 3^5
#include "stdio.h"
int main()
{
long long int testcase,b,c,N,a;
long long int pow2,pow3 = 1;
long long int m = 1000000007;
// input the power
scanf("%lld",&a); getchar();
scanf("%lld",&b); getchar();
// power of 2 (2^a)
for(int i = 1; i <= a; i++){
pow2 = pow2 * 2;
}
// power of 3 (3^b)
for(int j = 1; j <= b; j++){
pow3 = pow3 * 3;
}
// convert the big numbers into modulo
long long int i = 1;
i = (1*pow2) % m ;
long long int j = 1;
j = (1*pow3) % m;
// the result of first modulo times second modulo
printf("%lld\n", i*j);
// doesnt work for 2^100 * 3^5
return 0;
}
For a = 2 and b = 5 its gives the output of 972 (which is correct)
for a = 100 and b = 3 its gives 0 output.
Firstly, pow2 is uninitialized and therefore the behaviour is undefined. If initialized to 1, then the problem is that 2^100 does not fit in the long long int. The best fix is to take the modulo as often as possible.
// power of 2 (2^a)
for(int i = 1; i <= a; i++){
pow2 *= 2;
pow2 %= m;
}
// power of 3 (3^b)
for(int j = 1; j <= b; j++){
pow3 *= 3;
pow3 %= m;
}
Notice that this is still suboptimal - it is possible to calculate much larger powers by using exponentiation by squaring.
Finally you must note that the last product must be mod 1000000007 too, otherwise the result is larger than expected:
printf("%lld\n", i * j % m);

coding e^x function using Taylor Series without using math.h and factorial function

I am making simple calculator and it is e^x function part.
it works for positive number, but it doesn't for negative x.
How can I make it works for negative x too?`
double calculateEx(double x) {
double beforeResult = 1, afterResult = 1, term = 1, error = 1, i = 1, j;
while (error > 0.001) {
afterResult = beforeResult;
for (j = 1; j <= i; j++) {
term *= x;
}
term /= fact(i);
afterResult += term;
error = (afterResult - beforeResult) / afterResult;
if (error < 0) error * -1;
error *= 100;
beforeResult = afterResult;
term = 1;
i++;
}
return beforeResult;
}
double fact (double num) {
int i, j;
double total = 1;
for (i = 2; i <= num; i++) {
total = total * i;
}
return total;
}
When computing exponent via Taylor serie
exp(x) = 1 + x / 1 + x**2/2! + ... + x**n/n!
you don't want any factorials, please, notice that if n-1th term is
t(n-1) = x**(n-1)/(n-1)!
then
t(n) = x**n/n! = t(n-1) * x / n;
That's why all you have to implement is:
double calculateEx(double x) {
double term = 1.0;
double result = term;
/*
the only trick is that term can be positive as well as negative;
we should either use abs in any implementation or putr two conditions
*/
for (int n = 1; term > 0.001 || term < -0.001; ++n) {
term = term * x / n;
result += term;
}
return result;
}
OK, as I wrote in a comment above, I'd use <math.h> if at all possible, but since you asked the question:
To make it work with negative numbers, if x is negative, consider what happens if you negate it.
You can get rid of the factorial function by storing a table of factorials. You won't need that many elements.

Work out the overall progress (%) of three nested for loops

I have three nested for loops, each of which obviously have a limit. To calculate the progress of any one of the three for loops, all that I need to do is to divide the current iteration by the total number of iterations that the loop will make. However, given that there are three different for loops, how can I work out the overall percentage complete?
int iLimit = 10, jLimit = 24, kLimit = 37;
for (int i = 0; i < iLimit; i++) {
for (int j = 0; j < jLimit; j++) {
for (int k = 0; k < kLimit; k++) {
printf("Percentage Complete = %d", percentage);
}
}
}
I tried the following code, but it reset after the completion of each loop, reaching a percentage greater than 100.
float percentage = ((i + 1) / (float)iLimit) * ((j + 1) / (float)jLimit) * ((k + 1) / (float)kLimit) * 100;
You can easily calculate the "change in percentage per inner cycle"
const double percentChange = 1.0 / iLimit / jLimit / kLimit;
Note, this mathematically equivalent to 1/(iLimit*jLimit*kLimit), however if iLimitjLimitkLimit is sufficiently large, you'll have an overflow and unexpected behavior. It's still possible to have an underflow with the 1.0/... approach, but its far less likely.
int iLimit = 10, jLimit = 24, kLimit = 37;
const double percentChange = 1.0 / iLimit / jLimit / kLimit;
double percentage = 0;
for (int i = 0; i < iLimit; i++) {
for (int j = 0; j < jLimit; j++) {
for (int k = 0; k < kLimit; k++) {
percentage += percentChange;
printf("Percentage Complete = %d\n", (int)(percentage * 100));
}
}
}
If I do understand your question right, then I think the counter variables at each level (i.e. i, j, k) should have a different weightage in the %age formula. Let me explain what I mean: Each increment of j corresponds to kLimit iterations of the innermost loop. So, if you have only one level of nesting (say the outermost loop using i is not present), total number of loop iterations would be kLimit*jLimit and the percentage:
percentage = (100.0 * (j*kLimit + k + 1)) / (float)(kLimit*jLimit)
You got the idea? Its very easy to generalize this concept to the required level of nesting. I hope you can very well figure out the needed equation for your case. Anyways here is the final formula:
percentage = 100.0 * (kLimit * (i * jLimit + j) + k + 1) / (iLimit * jLimit * kLimit)
The total number of loops is iLimit * jLimit * kLimit, and so if you have an incrementing percentage in the inner loop, you can just print
100 * percentage / (iLimit * jLimit * kLimit)
Since you are using %d to print the percentage, you can limit everything to integer calculations. (And it avoids seeing meaningless 'exact' values such as 0.011261 for the first step.)
If you want to see properly rounded values, you can also use this:
printf("Percentage Complete = %d%%\r", (counter*200+iLimit * jLimit * kLimit) /
(2 * iLimit * jLimit * kLimit));
The \r at the end is a small refinement so each line will overprint the previous one.
Try this one:
int iLimit = 10, jLimit = 24, kLimit = 37;
float percentage;
for (int i = 0; i < iLimit; i++) {
for (int j = 0; j < jLimit; j++) {
for (int k = 0; k < kLimit; k++) {
percentage = ((k+1) + j * kLimit + i*jLimit*kLimit)/(float)(iLimit*jLimit*kLimit) * 100;
printf("Percentage Complete = %f\n", percentage);
}
}
}
This solution is very simmilar to the counter incrementation solution posted here.
The advantage for this solution is that I supplied a formula for the counter which depends on the i,j,k and the limits iLimit, jLimit, kLimit:
counter = (k+1) + j * kLimit + i*jLimit*kLimit
This way, you can find out the percentage when you know i, j, k without iterating through the loops.
Thus you can possibly reduce a O(iLimit * jLimit * kLimit) problem to a O(1) problem.
Remember that percentage is parts of 100.
To get 100 you need to do e.g. (iLimit * jLimit * kLimit) / (iLimit * jLimit * kLimit) * 100.
Each iteration of the loop takes 1 / (iLimit * jLimit * kLimit) parts of the whole.
To get the percentage, "simply" do e.g.
float percentage = ++counter / (float) (iLimit * jLimit * kLimit) * 100.0;
Remember to declare and initialize the counter variable before the loops.

Need a formula to calculate (i->0 to n-1 )π(n!/i!)

I need a formula to calculate the expression multiplication of (n!/i!) where i varies from 0 to n-1. So that I can implement it to a Code. trivial way exceed time limit.Any quick suggestions are welcome
x = (n!/i!) = (i+1) * (i+2) * ... * (n)
So, in pseudo-code (doing it in reverse order for increased efficiency):
x = 1;
result = 1;
for (j = n; j > 0; j--) {
x = x * j;
result = result * x; // Or + if you want the sum instead of the product
}
return result;
Note that you may need a bigint representation for x and result as they will overflow quickly.

complexity for a nested loop with varying internal loop

Very similar complexity examples. I am trying to understand as to how these questions vary. Exam coming up tomorrow :( Any shortcuts for find the complexities here.
CASE 1:
void doit(int N) {
while (N) {
for (int j = 0; j < N; j += 1) {}
N = N / 2;
}
}
CASE 2:
void doit(int N) {
while (N) {
for (int j = 0; j < N; j *= 4) {}
N = N / 2;
}
}
CASE 3:
void doit(int N) {
while (N) {
for (int j = 0; j < N; j *= 2) {}
N = N / 2;
}
}
Thank you so much!
void doit(int N) {
while (N) {
for (int j = 0; j < N; j += 1) {}
N = N / 2;
}
}
To find the O() of this, notice that we are dividing N by 2 each iteration. So, (not to insult your intelligence, but for completeness) the final non-zero iteration through the loop we will have N=1. The time before that we will have N=a(2), then before that N=a(4)... where 0< a < N (note those are non-inclusive bounds). So, this loop will execute a total of log(N) times, meaning the first iteration we see that N=a2^(floor(log(N))).
Why do we care about that? Well, it's a geometric series which has a nice closed form:
Sum = \sum_{k=0}^{\log(N)} a2^k = a*\frac{1-2^{\log N +1}}{1-2} = 2aN-a = O(N).
If someone can figure out how to get that latexy notation to display correctly for me I would really appreciate it.
You already have the answer to number 1 - O(n), as given by #NickO, here is an alternative explanation.
Denote the number of outer repeats of inner loop by T(N), and let the number of outer loops be h. Note that h = log_2(N)
T(N) = N + N/2 + ... + N / (2^i) + ... + 2 + 1
< 2N (sum of geometric series)
in O(N)
Number 3: is O((logN)^2)
Denote the number of outer repeats of inner loop by T(N), and let the number of outer loops be h. Note that h = log_2(N)
T(N) = log(N) + log(N/2) + log(N/4) + ... + log(1) (because log(a*b) = log(a) + log(b)
= log(N * (N/2) * (N/4) * ... * 1)
= log(N^h * (1 * 1/2 * 1/4 * .... * 1/N))
= log(N^h) + log(1 * 1/2 * 1/4 * .... * 1/N) (because log(a*b) = log(a) + log(b))
< log(N^h) + log(1)
= log(N^h) (log(1) = 0)
= h * log(N) (log(a^b) = b*log(a))
= (log(N))^2 (because h=log_2(N))
Number 2 is almost identical to number 3.
(In 2,3: assuming j starts from 1, not from 0, if this is not the case #WhozCraig giving the reason why it never breaks)

Resources