How to find a mistake in the calculation of the amounts - c++

I tried to complete a task with the calculation of the amounts. The task is Sn=(cosx/1)+((cosx+cos2x)/2)+...+((cosx+...+cosxn)/n);x - float, n - integer.
But the programm outputed zero in every situation.
Its c++ code written on DevC++5.11. I almost finished the code, but i cant find a mistake.
float funct(float x, float s, int n)
{
if (n < 1) {
cout << s;
return 0;
}
for (int i = n; i < 1; i--) {
float a = (cos(i * x)) / n;
s = s + a;
}
return funct(x, s, n - 1);
}
int main(void)
{
float x = 1, s = 0;
int n;
cin >> n;
funct(x, s, n);
}
I expect the output something like terible float numbers, but the actual output is zero.

for (int i = n; i < 1; i--)
Should be
for (int i = 1; i <= n; i++)
if you want it to loop from 1 to n

Related

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}

Floating Point Error With This Code Can someone help me

i am facing problem with this chinese remainder theoram
i am taking an input.txt file as input
and trying to generate an output.txt file but it says floating point error. when i am running with some specific input at that time it is working but for many test cases it is not working
#include <bits/stdc++.h>
#include <fstream>
#include <iostream>
using namespace std;
int ModInverse(int a, int m)
{
a = a % m;
for(int x = 1; x < m; x++)
if(((a * x) % m) == 1) return x;
}
int findMinX(int num[], int rem[], int k) {
int prod = 1;
for(int i = 1; i <= k; i++) prod *= num[i];
int result = 0;
for(int j = 1; j <= k; j++) {
int y = prod / num[j];
result = result + rem[j] * ModInverse(y, num[j]) * y;
}
return result % prod;
}
int main() {
ifstream infile;
infile.open("input.txt");
int n;
int num[100];
int rem[100];
infile >> n;
for(int i = 0; i < n; i++) infile >> num[i];
for(int i = 0; i < n; i++) infile >> rem[i];
infile.close();
int k = sizeof(num) / sizeof(num[0]);
ofstream myfile;
myfile.open("output.txt");
myfile << findMinX(num, rem, k);
myfile.close();
return 0;
}
These lines:
for(int i = 1; i <= k; i++)
for(int j = 1; j <= k; j++)
will cause i and j to go out of bounds.
Array indexing starts at 0 in C++, so you should use indexes 0 to k-1.
Do this instead:
for(int i = 0; i < k; i++)
for(int j = 0; j < k; j++)
Another thing worth checking up is this function:
int ModInverse(int a, int m)
{
a = a % m;
for(int x = 1; x < m; x++)
if(((a * x) % m) == 1) return x;
}
Given the wrong input, it'll exit the loop and return nothing, which causes undefined behaviour. Validate the input and print an error message if the file contains data you can't handle.
Here's an example of an input.txt that makes it crash for me:
5
1 2 3 4 5
2 3 4 5 6
Another cause for concern is that you use k instead of n in your call to the function:
myfile << findMinX(num, rem, k);
This means the function will always work on 100 values. Some of them may be uninitialized, and again, undefined behaviour.

how to Calculate this series

#include <iostream>
#include <math.h>
using namespace std;
int fact(int number)
{
unsigned long long int p = 1;
if (number == 0) {
return p;
}
for (int i = 1; number >= i; i++) {
p = p * i;
}
return p;
}
int main()
{
long long int a, x, sum = 0, result;
int n ;
cin >> a;
cin >> x;
cin >> n;
for (int k = 0; n >= k; k++) {
result = fact(n) / (fact(k) * fact(n - k));
sum = sum + (result * pow(x, k) * pow(a, n - k));
}
cout << sum;
return 0;
}
I want to calculate this series
So I considered the long long int sum, but the sum number sometimes gets too big. What can I do to save the sum number without using library?
First of all I would suggest to use binomial theorem -- what you are computing is just pow(x+a, n)
If you want to do this through series, do not compute the binomial coefficient using factorials but something like this
int bin_coeff(int n, int k){
int lim = k > n/2 ? k : n - k;
int sum = 1;
for (int i = n; i > lim; i--){
sum *= i;
}
for (int i = 2; i < (n - lim + 1); i++){
sum /= i;
}
return sum;
}

Structure use in a function C++

I want to create a function that returns a structure, then run a loop for that function. The idea is basically to calculate the maximum sum, start point and end point of a set of n numbers (1000 in this case) and this for 10 lines in a text file
struct triple
{
float Max;
int sp;
int ep;
};
triple Max_line(string linename, int n)
{
int k, i, stp, enp, j;
triple Result;
float Maxi;
float T[n];
string s;
stringstream ss(linename);
j = 0;
Maxi = 0;
stp = 0;
enp = 0;
while (getline(ss, s, ',')and k < n)
{
T[j] = atof(s.c_str());
j++;
}
for (i = 0; i < n - 1; i++)
{
int k;
float S;
S = T[i];
k = i;
while (k < n - 1)
{
S = S + T[k + 1];
if (S > Maxi)
{
Maxi = S;
stp = i + 1;
enp = k + 2;
}
k++;
}
}
Result = { Maxi, stp, enp }
return Result;
}
int main(int argc, char *argv[]) {
int i, j;
triple fin;
fstream myfile("1000.txt"); //extract data from a file containing 10 lines each has 1000 different numbers
string a, b;
getline(myfile, a); //skip the first line
for (i = 0; i < 10; i++)
{
getline(myfile, b);
fin = Max_line(b, 1000);
cout << fin.Max << ";" << fin.sp << ";" << fin.ep << endl;
}
return 0;
}
When I printed the results inside the Max_line function it gave me the right values, I don't understand why it's not working inside the for loop.
Can anyone help me with that please?

Fibonacci numbers - dynamic array

I want to write Fibonacci number program, using dynamic array in function. If I want to initialize array in the function, where I must delete this array? Here is code:
#include <iostream>
using namespace std;
int* fibo(int);
int main()
{
int *fibonacci, n;
cout << "Enter how many fibonacci numbers you want to print: ";
cin >> n;
fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
//for (int i = 0; i < n; i++)
//delete w_fibo[i];
//delete[] w_fibo;
return 0;
}
int* fibo(int n)
{
int* w_fibo = new int[n];
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}
You don't have to initialize the array! a better dynamic Fibonacci presentation could be like this:
int fib2 (int n) {
int i = 1, j = 0;
for (int k = 0; k < n; k++) { // The loop begins to work real after one loop (k == 1). Sounds interesting!
j += i; // Adds the produced number to the last member of the sequence and makes a new sentence.
i = j - i; // Produces the number that should be added to the sequence.
}
return j;
}
and you can get the n-th fib number using this method. It's O(log(n)) so it's so efficient.`
int fib3 (int n) {
int i = 1, j = 0, k = 0, h = 1, t=0;
while (n > 0) {
if (n % 2) { // |
t = j * h; // |
j = i * h + j * k + t;
i = i * k + t;
}
t = h * h;
h = 2 * k * h + t;
k = k * k + t;
n /= 2;
}
return j;
}
If you allocate a std::vector<int> inside fibo() and reserve enough memory, and then return it by value, the memory allocation is taken care for you by the compiler:
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> fibo(int n)
{
std::vector<int> w_fibo;
w_fibo.reserve(n);
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}
int main()
{
int n = 10;
std::vector<int> fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
}
Live Example.
NOTE: This is guaranteed to avoid needlessly copying in C++11 (move semantics) and is likely to do so in C++98 (copy-elision using the return-value-optimization).
This is an old question, but just in case someone happens to pass by this might be helpful.
If you need a efficient method to get the nth Fibonacci number, we have a O(1) time complexity procedure.
It is based on Binet's formula, which I think our friends over at math.se will be better at proving, so feel free to follow that link.
The formula itself is, given a=1.618 and b=-0.618 (these are approximate values)
the n-th term is (a^n - b^n)/2.236. A good way to round that off(since we are using approximate values) would be adding 0.5 and taking the floor function.
math.floor(((math.pow(1.618,n)-math.pow(-0.618,n))/2.236 + 0.5)