I am creating a script that calculates the sum of first n Fibonacci numbers and returns the last digit of the sum.
The python script works perfect but the C++ script does not and the logic is same.
Any help will be appreciated.
Python Code
def calc_fib(n):
f = [0, 1]
for i in range(2, 61):
f.insert(i, (f[i-1] + f[i-2]) % 10)
rem = n % 60
quotient = (n - rem) / 60
return int((sum(f) * quotient + sum(f[0: rem+1])) % 10)
n = int(input())
print(calc_fib(n))
C++ Code
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
long long fibonacci_sum_last_digit(long long n) {
vector<int> f(n + 1);
f[0] = 0;
f[1] = 1;
for (int i = 2; i <= 60; i++){
f[i] = (f[i-1] + f[i-2]) % 10;
}
int rem = n % 60;
int quotient = (n - rem) / 60;
return (accumulate(f.begin(), f.end(), 0) * quotient + accumulate(f.begin(), f.begin() + rem + 1, 0)) % 10;
}
int main() {
int n;
cin >> n;
if (n <= 1)
cout << n;
else
cout << fibonacci_sum_last_digit(n) << '\n';
return 0;
}
vector<int> f(n + 1);
f[0] = 0;
f[1] = 1;
for (int i = 2; i <= 60; i++){
f[i] = (f[i-1] + f[i-2]) % 10;
}
The vector is size n+1 and you access until 60 => it's a bug
This should fix :
vector<int> f(60 + 1);
Or
vector<int> f;
f.push_back(0);
f.push_back(1);
for (int i = 2; i <= 60; i++){
f.push_back((f[i-1] + f[i-2]) % 10);
}
Related
im struggle to solve this math formula and i don't see where i made mistake. Little hint would be welcome.
using namespace std;
double sum, quo;
int n, i;
sum = 0;
quo = 1;
for (n = 1; n <= 5; n++) {
sum = sum + quo;
}
for (i = 1; i <= 6; i++) {
quo = quo * (n + i);
}
sum = sum + quo;
cout << (sum);}
Answer should be 569520, but in my code is 665285
As #Yksisarvinen said,
Hint
Multiplication is inside summation in the formula.
Hint 2
You can use 2 for loop inside each others
Stop here and try it yourself then come back to see the answer.
the answer :
#include <iostream>
#include <windows.h>
using namespace std;
int main() {
int sum, quo;
int n, i;
sum = 0;
quo = 1;
for (n = 1; n <= 5; n++) {
for (i = 1; i <= 6; i++) {
quo *= (n + i);
}
sum+=quo;
quo =1;
}
cout << (sum);
}
It's been a while since I've done this sort of maths, but I think your nesting is incorrect.
What I think the formula is saying is:
((1 + 1) * (1 + 2) * (1 + 3) ...)
+
((2 + 1) * (2 + 2) * (2 + 3) ...)
+
...
However, you're summing loop only apply to i=1. I think this is just an incorrectly placed brace.
for (n = 1; n <= 5; n++) {
//The n loop should encompass the whole of the i loop
//And you should only update sum at the end
double quo = 1;
for (i = 1; i <= 6; i++) {
quo = quo * (n + i);
}
sum = sum + quo;
}
A Magic Fraction for N is one that has the following properties:
It is a proper fraction (The value is < 1)
It cannot be reduced further (The GCD of the numerator and the denominator is 1)
The product of the numerator and the denominator is factorial of N. i.e. if a/b is the fraction, then a*b = N!
Examples of Magic Fractions are:
1/2 [ gcd(1,2) = 1 and 1*2=2! ]
2/3 [ gcd(2,3) = 1 and 2*3=3! ]
3/8 [ gcd(3,8) = 1 and 3*8=4! ]
2/12 for example, is not a magic fraction, as even though 2*12=4!, gcd(2,12) != 1
And Magic fractions for number 3 are: 2/3 and 1/6 (since both of them satisfy the above criteria, are of the form a/b where a*b = 3!)
Now given a number N, you need to print the total number of magic fractions that exist, for all numbers between 1 and N (include magic fractions for N, too).
Can anybody tell me what is modPow function doing?
Refer the link to see the question, that will give an idea why this code.
using namespace std;
#define ll long long int
#define S(n) scanf("%lld", &n)
ll MOD = 1e18 + 7;
ll modPow(ll a, ll b)
{
ll res = 1;
a %= MOD;
for (; b; b >>= 1) {
if (b & 1)
res = res * a % MOD;
a = a * a % MOD;
}
return res;
}
int main()
{
ll i, j;
ll va = 1;
ll sum = 0;
ll prime[1000] = { 0 };
for (i = 2; i <= 500; i++) {
if (prime[i] == 0)
for (j = 2 * i; j <= 500; j += i)
prime[j] = 1;
}
ll val[600] = { 0 };
val[1] = 0;
val[2] = 1;
ll co = 0;
for (i = 3; i <= 500; i++) {
if (prime[i] == 0) {
co++;
}
ll t1 = modPow(2, co);
val[i] = t1 + val[i - 1];
val[i] %= MOD;
// cout << i << " " << val[i] << "\n";
}
ll n;
S(n);
cout << val[n] << "\n";
}
How to create all possible numbers, starting from a given one, where all digits of the new ones are moved one slot to the right? For example if we have 1234. I want to generate 4123, 3412 and 2341.
What I have come out with so far is this:
int move_digits(int a)
{
int aux = 0;
aux = a % 10;
for(int i=pow(10, (number_digits(a) - 1)); i>0; i=i/10)
aux = aux * 10 + ((a % i) / (i/10));
return aux;
}
But it doesn't work.
The subprogram number_digits looks like this (it just counts how many digits the given number has):
int number_digits(int a)
{
int ct = 0;
while(a != 0)
{
a = a/10;
ct++;
}
return ct;
}
I think there is no need to write separate function number_digits.
I would write function move_digits simpler
#include <iostream>
#include <cmath>
int move_digits( int x )
{
int y = x;
double n = 0.0;
while ( y /= 10 ) ++n;
return ( x / 10 + x % 10 * std::pow( 10.0, n ) );
}
int main()
{
int x = 1234;
std::cout << x << std::endl;
std::cout << move_digits( x ) << std::endl;
}
Retrieving the last digit of n: n % 10.
To "cut off" the last digit, you could use number / 10.
Say you have a three-digit number n, then you can prepend a new digit d using 1000 * d + n
That said, you probably want to compute
aux = pow(10, number_digits - 1) * (aux % 10) + (aux / 10)
Calculatea/(number_digits(a) - 1) and a%(number_digits(a) - 1)
And your answer is (a%(number_digits(a) - 1))*10 + a/(number_digits(a) - 1)
int i =0 ;
int len = number_digits(a);
while(i < len){
cout << (a%(len - 1))*10 + a/(len - 1) <<endl;
a = (a%(len - 1))*10 + a/(len - 1);
}
void move_digits(int a)
{
int digits = 0;
int b = a;
while(b / 10 ){
digits++;
b = b / 10;
}
for (int i = 0; i < digits; ++i)
{
int c = a / 10;
int d = a % 10;
int res = c + pow(10, digits) * d;
printf("%d\n", res);
a = res;
}
printf("\n");
}
int main()
{
move_digits(12345);
}
I'm trying to make a parallel version of "Harmonic Progression Sum" problem using MPI.
But I'm new with MPI and I don't know how to run this method with MPI, because it isn't work.
Parallel Program:
//#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <mpi.h>
#define d 10 //Numbers of Digits (Example: 5 => 0,xxxxx)
#define n 1000 //Value of N (Example: 5 => 1/1 + 1/2 + 1/3 + 1/4 + 1/5)
using namespace std;
int numProcess, rank, msg, source, dest, tag, qtd_elemento;
int escravo(long unsigned int *digits, int ValueEnd)
{
MPI_Status status;
MPI_Recv(digits, (d + 11), MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
for (int i = 1; i <= ValueEnd; ++i) {
long unsigned int remainder = 1;
for (long unsigned int digit = 0; digit < d + 11 && remainder; ++digit) {
long unsigned int div = remainder / i;
long unsigned int mod = remainder % i;
digits[digit] += div;
remainder = mod * 10;
}
}
MPI_Send(&digits, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
}
void HPSSeguencial(char* output) {
long unsigned int digits[d + 11];
int DivN = n / 4; //Limiting slave.
for (int digit = 0; digit < d + 11; ++digit)
digits[digit] = 0;
if (rank != 0){
escravo(digits, (DivN * 1 ) );
escravo(digits, (DivN * 2 ) );
escravo(digits, (DivN * 3 ) );
escravo(digits, (DivN * 4 ) );
}
for (int i = d + 11 - 1; i > 0; --i) {
digits[i - 1] += digits[i] / 10;
digits[i] %= 10;
}
if (digits[d + 1] >= 5) {
++digits[d];
}
for (int i = d; i > 0; --i) {
digits[i - 1] += digits[i] / 10;
digits[i] %= 10;
}
stringstream stringstreamA;
stringstreamA << digits[0] << ",";
for (int i = 1; i <= d; ++i) {
stringstreamA << digits[i];
}
string stringA = stringstreamA.str();
stringA.copy(output, stringA.size());
}
int main() {
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &numProcess);
char output[d + 10];
HPSSeguencial(output);
cout << output << endl;
MPI_Finalize();
system("PAUSE");
return 0;
}
Original Code
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <time.h>
#define d 10 //Numbers of Digits (Example: 5 => 0,xxxxx)
#define n 1000 //Value of N (Example: 5 => 1/1 + 1/2 + 1/3 + 1/4 + 1/5)
using namespace std;
void HPS(char* output) {
long unsigned int digits[d + 11];
for (int digit = 0; digit < d + 11; ++digit)
digits[digit] = 0;
for (int i = 1; i <= n; ++i) {
long unsigned int remainder = 1;
for (long unsigned int digit = 0; digit < d + 11 && remainder; ++digit) {
long unsigned int div = remainder / i;
long unsigned int mod = remainder % i;
digits[digit] += div;
remainder = mod * 10;
}
}
for (int i = d + 11 - 1; i > 0; --i) {
digits[i - 1] += digits[i] / 10;
digits[i] %= 10;
}
if (digits[d + 1] >= 5) {
++digits[d];
}
for (int i = d; i > 0; --i) {
digits[i - 1] += digits[i] / 10;
digits[i] %= 10;
}
stringstream stringstreamA;
stringstreamA << digits[0] << ",";
for (int i = 1; i <= d; ++i) {
stringstreamA << digits[i];
}
string stringA = stringstreamA.str();
stringA.copy(output, stringA.size());
}
int main() {
char output[d + 10];
HPS(output);
cout << output<< endl;
system("PAUSE");
return 0;
}
Examples:
Input:
#define d 10
#define n 1000
Output:
7,4854708606╠╠╠╠╠╠╠╠╠╠╠╠
Input:
#define d 12
#define n 7
Output:
2,592857142857╠╠╠╠╠╠╠╠╠╠╠╠╠╠ÀÂ♂ü─¨#
Regards
Original Code
http://regulus.pcs.usp.br/marathon/current/warmup.pdf
I am assuming that you want to parallelize this part:
for (int i = 1; i <= ValueEnd; ++i)
{
long unsigned int remainder = 1;
for (long unsigned int digit = 0; digit < d + 11 && remainder; ++digit)
{
long unsigned int div = remainder / i;
long unsigned int mod = remainder % i;
digits[digit] += div;
remainder = mod * 10;
}
}
You can divide each for iteration by each MPI process:
int idP = getProcessId(), numP = numberProcess();
for (int i = idP; i <= ValueEnd; i+=numP)
{
...
}
The getProcessId() gives you the process ID and numberProcess() gives you the number of process:
int getProcessId(){
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
return rank;
}
// Get number of process
int numberProcess(){
int numProc;
MPI_Comm_size(MPI_COMM_WORLD, &numProc);
return numProc;
}
Each process will have a copy of the array digits; After the parallel for, the master process collects the results from all slaves process using a MPI_reduce. Or if you want to combine the values from all processes and distribute the result back to all processes you can use MPI_Allreduce.
long unsigned int digits[d + 11];
int DivN = n / 4; //Limiting slave.
for (int digit = 0; digit < d + 11; ++digit)
digits[digit] = 0;
if (rank != 0){
escravo(digits, (DivN * 1 ) );
escravo(digits, (DivN * 2 ) );
escravo(digits, (DivN * 3 ) );
escravo(digits, (DivN * 4 ) );
}
According to the code above process 0 will not execute the method escravo. Furthermore, you are not distributing correctly the work among processes. Process 1 will execute the out for loop inside the method escravo from 1 until n/4, but then process 2 will execute from 1 until 2n/4... Thus, you have different processes executing the same iterations, when what you really want is to divide these iterations among process.
This is a problem I have been struggling for a week, coming back just to give up after wasted hours...
I am supposed to find coefficents for the following Laguerre polynomial:
P0(x) = 1
P1(x) = 1 - x
Pn(x) = ((2n - 1 - x) / n) * P(n-1) - ((n - 1) / n) * P(n-2)
I believe there is an error in my implementation, because for some reason the coefficents I get seem way too big. This is the output this program generates:
a1 = -190.234
a2 = -295.833
a3 = 378.283
a4 = -939.537
a5 = 774.861
a6 = -400.612
Description of code (given below):
If you scroll the code down a little to the part where I declare array, you'll find given x's and y's.
The function polynomial just fills an array with values of said polynomial for certain x. It's a recursive function. I believe it works well, because I have checked the output values.
The gauss function finds coefficents by performing Gaussian elimination on output array. I think this is where the problems begin. I am wondering, if there's a mistake in this code or perhaps my method of veryfying results is bad? I am trying to verify them like that:
-190.234 * 1.5 ^ 5 - 295.833 * 1.5 ^ 4 ... - 400.612 = -3017,817625 =/= 2
Code:
#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
double polynomial(int i, int j, double **tab)
{
double n = i;
double **array = tab;
double x = array[j][0];
if (i == 0) {
return 1;
} else if (i == 1) {
return 1 - x;
} else {
double minusone = polynomial(i - 1, j, array);
double minustwo = polynomial(i - 2, j, array);
double result = (((2.0 * n) - 1 - x) / n) * minusone - ((n - 1.0) / n) * minustwo;
return result;
}
}
int gauss(int n, double tab[6][7], double results[7])
{
double multiplier, divider;
for (int m = 0; m <= n; m++)
{
for (int i = m + 1; i <= n; i++)
{
multiplier = tab[i][m];
divider = tab[m][m];
if (divider == 0) {
return 1;
}
for (int j = m; j <= n; j++)
{
if (i == n) {
break;
}
tab[i][j] = (tab[m][j] * multiplier / divider) - tab[i][j];
}
for (int j = m; j <= n; j++) {
tab[i - 1][j] = tab[i - 1][j] / divider;
}
}
}
double s = 0;
results[n - 1] = tab[n - 1][n];
int y = 0;
for (int i = n-2; i >= 0; i--)
{
s = 0;
y++;
for (int x = 0; x < n; x++)
{
s = s + (tab[i][n - 1 - x] * results[n-(x + 1)]);
if (y == x + 1) {
break;
}
}
results[i] = tab[i][n] - s;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int num;
double **array;
array = new double*[5];
for (int i = 0; i <= 5; i++)
{
array[i] = new double[2];
}
//i 0 1 2 3 4 5
array[0][0] = 1.5; //xi 1.5 2 2.5 3.5 3.8 4.1
array[0][1] = 2; //yi 2 5 -1 0.5 3 7
array[1][0] = 2;
array[1][1] = 5;
array[2][0] = 2.5;
array[2][1] = -1;
array[3][0] = 3.5;
array[3][1] = 0.5;
array[4][0] = 3.8;
array[4][1] = 3;
array[5][0] = 4.1;
array[5][1] = 7;
double W[6][7]; //n + 1
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 5; j++)
{
W[i][j] = polynomial(j, i, array);
}
W[i][6] = array[i][1];
}
for (int i = 0; i <= 5; i++)
{
for (int j = 0; j <= 6; j++)
{
cout << W[i][j] << "\t";
}
cout << endl;
}
double results[6];
gauss(6, W, results);
for (int i = 0; i < 6; i++) {
cout << "a" << i + 1 << " = " << results[i] << endl;
}
_getch();
return 0;
}
I believe your interpretation of the recursive polynomial generation either needs revising or is a bit too clever for me.
given P[0][5] = {1,0,0,0,0,...}; P[1][5]={1,-1,0,0,0,...};
then P[2] is a*P[0] + convolution(P[1], { c, d });
where a = -((n - 1) / n)
c = (2n - 1)/n and d= - 1/n
This can be generalized: P[n] == a*P[n-2] + conv(P[n-1], { c,d });
In every step there is involved a polynomial multiplication with (c + d*x), which increases the degree by one (just by one...) and adding to P[n-1] multiplied with a scalar a.
Then most likely the interpolation factor x is in range [0..1].
(convolution means, that you should implement polynomial multiplication, which luckily is easy...)
[a,b,c,d]
* [e,f]
------------------
af,bf,cf,df +
ae,be,ce,de, 0 +
--------------------------
(= coefficients of the final polynomial)
The definition of P1(x) = x - 1 is not implemented as stated. You have 1 - x in the computation.
I did not look any further.