#include<iostream>
#include<vector>
#include<cstdlib>
#include <cassert>
using namespace std;
long long int LastDigitofSumofFibonacci(int n){long long int first=0;
long long int second=1;
long long int fibOfn;
long long int sum=1;
vector<long long int> V;
V.push_back(first);
V.push_back(second);
if(n==0) return first;
else if(n==1) return second;
else{
for(int i=2;i<60;i++){
fibOfn=first+second;
first=second;
second=fibOfn;
sum=sum+fibOfn;
//cout<<"i "<<i<<" fibOfn "<<fibOfn<<" fibOfnlastdigit "<<fibOfnlastdigit<<" first "<<first<<" second "<<second<<" sum "<<sum;
//cout<<endl;
sum=sum%10;
V.push_back(sum);
}
}
//for(auto element:V)
//cout<<element<<" ";
//cout<<endl;
//cout<<(n)%60<<endl;
return V[(n)%60];
}
int main(){
int n;
cin>>n;
long long int Base=LastDigitofSumofFibonacci(n);
cout<<Base<<endl;
}
In this I am trying to calculate the the last digit of Fibonacci series. I know and also read from net that last digit follow pattern of 60(0-59). from that concept wise I think my code is OK. but still I am unable to get the correct answers for large digit number.
I cleaned up the code a bit and fixed the issue with second not being computed % 10.
Since only the last digit is relevant all variables can be just int, no need for long long int to store a single digit. It would actually save ram to use uint8_t as type for the cache, but 60 bytes or 240 bytes isn't going to make a difference here.
The result repeats every 60 steps, which is the basis for the algorithm. But why compute this every time the function gets called? So lets make a static array so the computation only happens once. Lets go one step further with constinit and compute it at compile time.
As last change I made the argument to LastDigitofSumofFibonacci unsigned int. Unless you want to extend the fibonacci series backwards into the negative and extend the algorithm. unsigned int generates better code for n % 60.
#include <iostream>
#include <array>
int LastDigitofSumofFibonacci(unsigned int n) {
// The last digit of `fib(n)` and their sum repeats every 60 steps.
// https://en.wikipedia.org/wiki/Pisano_period
// Compute the first 60 values as lookup table at compile time.
static constinit std::array<int, 60> cache = []() {
int first = 0, second = 1;
std::array<int, 60> a{0, 1};
for (int i = 2; i < 60; i++) {
int t = first + second;
first = second;
second = t % 10;
a[i] = (a[i - 1] + t) % 10;
}
return a;
}();
// and now just look up the answer at run time.
return cache[n % 60];
}
int main(){
int n;
std::cin >> n;
std::cout << LastDigitofSumofFibonacci(n) << std::endl;
}
Somehow the code got a lot shorter just from eliminating some overhead here and there.
the question can be viewed on : https://www.hackerrank.com/contests/projecteuler/challenges/euler002/problem
when i test against my own input, i find it to be correct but hacker-rank shows all test cases as failed
my code is as follows :
#include<iostream>
using namespace std;
int retevenfib(unsigned long int &a,unsigned long int &b);
int main(){
unsigned long int fib1 = 1,fib2 = 2,hold = 2;
double evensum;
cout<<"enter no of tries:";
int t;
cin>>t;
cout<<"enter items sequentially: ";
long int numarr[20];
for(int i = 0; i < t ; i++)
cin>>numarr[i];
for (int j = 0; j < t; j++)
{
evensum = 0;
hold = 2; fib1 = 1; fib2 = 2;
while(fib2 < numarr[j])
{
evensum += hold;
hold = retevenfib(fib1,fib2);
}
cout<<evensum<<endl;
}
return 0;
}
int retevenfib(unsigned long int &a,unsigned long int &b)
{
for(int i = 0; i < 3; i++)
{
int temp = a + b;
a = b;
b = temp;
}
return b;
}
The very good message is: You still have the chance to go away from all this nonesense pages. I understand that you wonder why it fails, even for numbers below 20.
You need to understand that those pages ask for exact input and exact output. So, by writing:
cout<<"enter no of tries:";
cout<<"enter items sequentially: ";
you already lost the game.
Because that is not the expected output. The output shall just show the sum.
And the input is guaranteed to be correct. So, if you expect an integer, then normally you need to check the input. Because users normal users could enter "abc" and press enter. This will never happen here. So, you will never learn to use basic IO correctly.
You need to understand that there are no human beeings checking your program. Only scripts will run and push in some input and check the output exactly.
And because you do not yet know that, you have a chance to go away from those pages.
Now to the main problem: Your array. You define an array with 20 elements. And you maybe try to read 123 values in that array. This creates an out of bound error (a catastrophy) and the result is at least undefined behaviour or, also very likely, a crash of your program.
My guess would be that, if your configure your compiler for high warning levels, then you would get a corresponding message.
You do not need an array in the first place. You can omit it and simply do the calculation for each test.
Next advise. If you really want to use C++, then do never use C-Style arrays. Always use other containers like for example std::veector or std::array. There is no reason of whatsoever to use C-Style arrays in C++.
Next problem: You need to use the correct data types. For such big numbers as 10^16, an unsigned long is not big enough. It will overflow.
So please use unsigned long long or uint64_t instead.
Basically, in your whole program there is no need for any signed value at all. You should use unsigned everywhere.
Then at last, you could use "speaking" variable names. Then your program could look like the below (without any optimzation):
#include<iostream>
// Calculate the next even Fibonacci Number
// Take advantage of the fact, that every 3rd Fibonacci number will be even
unsigned long long getNextEvenFibonacciNumber(unsigned long long& previousPreviousFibonacciNumber,
unsigned long long& previousFibonacciNumber)
{
// Calculate 3 times the next Fibonacci number to get an even value
for (size_t i{}; i < 3u; ++i)
{
unsigned long long temp = previousPreviousFibonacciNumber + previousFibonacciNumber;
previousPreviousFibonacciNumber = previousFibonacciNumber;
previousFibonacciNumber = temp;
}
// This is now the next even Fibonacci number
return previousFibonacciNumber;
}
int main() {
// Here we store the number of test cases
size_t numberOfTestCases{};
// Get number of test cases from script
std::cin >> numberOfTestCases;
// For all test cases . . .
while (numberOfTestCases--) {
// OK, up to what number shall we perform the check
unsigned long long largestFibonacciNumberToCheck{};
std::cin >> largestFibonacciNumberToCheck;
// Some temporaries for our calculation
unsigned long long previousPreviousFibonacciNumber = 1ull;
unsigned long long previousFibonacciNumber = 2ull;
unsigned long long currentFibonacciNumber = 2ull;
unsigned long long sumOfEvenFibonacciNumbers{};
// Now, get all even Fibonacci numbers and summ them up
while (previousFibonacciNumber < largestFibonacciNumberToCheck)
{
sumOfEvenFibonacciNumbers += currentFibonacciNumber;
currentFibonacciNumber = getNextEvenFibonacciNumber(previousPreviousFibonacciNumber, previousFibonacciNumber);
}
// Show result
std::cout << sumOfEvenFibonacciNumbers << '\n';
}
return 0;
}
Comments will add quality to the code.
Your subfunction should be optimized.
And, if you wanted to win the contest, then you could precalulate all (below 30) Even-Fibonacci-Number-Sums and put them, togehter with an input range, in a compile time constexpr std::array, and just look up the value . . .
See the below example. Short, fast, easy
#include <iostream>
#include <array>
#include <algorithm>
#include <iterator>
struct SumOfEvenFib {
unsigned long long fibNum;
unsigned long long sum;
friend bool operator < (const unsigned long long& v, const SumOfEvenFib& f) { return v < f.fibNum; }
};
constexpr std::array<SumOfEvenFib, 27u> SOEF {{{2, 2}, { 8, 10 }, { 34, 44 }, { 144, 188 }, { 610, 798 }, { 2584, 3382 }, { 10946, 14328 }, { 46368, 60696 }, { 196418, 257114 }, { 832040, 1089154 },
{ 3524578, 4613732 },{ 14930352, 19544084 }, { 63245986, 82790070 }, { 267914296, 350704366 },{ 1134903170, 1485607536 }, { 4807526976, 6293134512 }, { 20365011074, 26658145586 } ,
{ 86267571272, 112925716858 }, { 365435296162, 478361013020 }, { 1548008755920, 2026369768940 }, { 6557470319842, 8583840088782 }, { 27777890035288, 36361730124070 },
{ 117669030460994, 154030760585064 }, { 498454011879264, 652484772464328 }, { 2111485077978050, 2763969850442378 }, { 8944394323791464, 11708364174233842 }, { 37889062373143906, 49597426547377748 } } };
int main() {
// Here we store the number of test cases
size_t numberOfTestCases{};
// Get number of test cases from script
std::cin >> numberOfTestCases;
// For all test cases . . .
while (numberOfTestCases--) {
// OK, up to what number shall we perform the summing up
unsigned long long largestFibonacciNumberToCheck{};
std::cin >> largestFibonacciNumberToCheck;
// Show sum
std::cout << std::prev(std::upper_bound(SOEF.begin(), SOEF.end(), largestFibonacciNumberToCheck))->sum << '\n';
}
return 0;
}
And for Hardcore C++ programmers, we generate the array automatically
#include <iostream>
#include <array>
#include <algorithm>
#include <iterator>
// ----------------------------------------------------------------------
// All the following wioll be done during compile time
// Constexpr function to calculate the nth even Fibonacci number
constexpr unsigned long long getEvenFibonacciNumber(size_t index) {
// Initialize first two even numbers
unsigned long long f1{ 0 }, f2{ 2 };
// calculating Fibonacci value
while (--index) {
// get next even value of Fibonacci sequence
unsigned long long f3 = 4 * f2 + f1;
// Move to next even number
f1 = f2;
f2 = f3;
}
return f2;
}
// Get nth even sum of Fibonacci numbers
constexpr unsigned long long getSumForEvenFibonacci(size_t index) {
// Initialize first two even prime numbers
// and their sum
unsigned long long f1{0}, f2{2}, sum{2};
// calculating sum of even Fibonacci value
while (--index) {
// get next even value of Fibonacci sequence
unsigned long long f3 = 4 * f2 + f1;
// Move to next even number and update sum
f1 = f2;
f2 = f3;
sum += f2;
}
return sum;
}
// Here we will store ven Fibonacci numbers and their respective sums
struct SumOfEvenFib {
unsigned long long fibNum;
unsigned long long sum;
friend bool operator < (const unsigned long long& v, const SumOfEvenFib& f) { return v < f.fibNum; }
};
// We will automatically build an array of even numbers and sums during compile time
// Generate a std::array with n elements
template <size_t... ManyIndices>
constexpr auto generateArrayHelper(std::integer_sequence<size_t, ManyIndices...>) noexcept {
return std::array<SumOfEvenFib, sizeof...(ManyIndices)>{ { {getEvenFibonacciNumber(ManyIndices + 1), getSumForEvenFibonacci(ManyIndices + 1)}...}};
};
// You may check with Binets formula
constexpr size_t MaxIndexFor64BitValue = 30u;
// Generate the required number of items
constexpr auto generateArray()noexcept {
return generateArrayHelper(std::make_integer_sequence<size_t, MaxIndexFor64BitValue >());
}
// This is an constexpr array of even Fibonacci numbers and its sums
constexpr auto SOEF = generateArray();
// ----------------------------------------------------------------------
int main() {
// Here we store the number of test cases
size_t numberOfTestCases{};
// Get number of test cases from script
std::cin >> numberOfTestCases;
// For all test cases . . .
while (numberOfTestCases--) {
// OK, up to what number shall we perform the summing up
unsigned long long largestFibonacciNumberToCheck{};
std::cin >> largestFibonacciNumberToCheck;
// Show sum
std::cout << std::prev(std::upper_bound(SOEF.begin(), SOEF.end(), largestFibonacciNumberToCheck))->sum << '\n';
}
return 0;
}
Tested with MSVC 19, Clang 11 and gcc 10
Compiled with C++17
I compiled and run in my computer, and it executes correctly. I tried IDEONE, and I got a successful answer.
But when I submit it in SPOJ, I'm getting a wrong answer. Is something wrong in this implementation?
#include <iostream>
#include <cstdio>
using namespace std;
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int t;
int n;
cout << "";
cin >> t;
for (int i = 0; i < t; i++) {
cout << "";
cin >> n;
printf("%d\n", factorial(n));
}
return 0;
}
The problem with the above code is due to the finite space we can use to store the value of an int. On a 32-bit machine, int's have 32 bits (value 0 or 1), which means that the maximum value an unsigned int can have is (2^31 - 1) and the maximum value an int can have is (2^30 - 1) (since it needs one bit to denote whether it is positive or negative, while the unsigned int is always positive and can devote that bit to just regular value).
Now, that aside, you should look into ways of storing the value of a very large number in a different data structure! Maybe an array would be a good choice...
Just to brainstorm, imagine creating an int bigInteger[100] (that should be large enough to hold 100!). To multiply two of your numbers, you could then implement a bitMultiplication(int bitNum[], int num) function that would take in your array by reference and perform bitwise multiplication (see the following post for details: Multiplying using Bitwise Operators).
Use that bitMulitiplication(int bitNum[], int num) instead of the regular multiplication in your recursive factorial function, and you should have a function that works on large n!
I found two ways of conversion from any base to base 10 . the first one is the normal one we do in colleges like 521(base-15) ---> (5*15^2)+(2*15^1)+(1*15^0)=1125+30+1 = 1156 (base-10) . my problem is that i applied both methods to a number (1023456789ABCDE(Base-15)) but i am getting different result . google code jam accepts the value generated from second method only for this particular number (i.e 1023456789ABCDE(Base-15)) . for all other cases both generates same results . whats big deal with this special number ?? can anybody suggest ...
#include <iostream>
#include <math.h>
using namespace std;
int main()
{ //number in base 15 is 1023456789ABCDE
int value[15]={1,0,2,3,4,5,6,7,8,9,10,11,12,13,14};
int base =15;
unsigned long long sum=0;
for (int i=0;i<15;i++)
{
sum+=(pow(base,i)*value[14-i]);
}
cout << sum << endl;
//this prints 29480883458974408
sum=0;
for (int i=0;i<15;i++)
{
sum=(sum*base)+value[i];
}
cout << sum << endl;
//this prints 29480883458974409
return 0;
}
Consider using std::stol(ref) to convert a string into a long.
It let you choose the base to use, here an example for your number wiuth base 15.
int main()
{
std::string s = "1023456789ABCDE";
long n = std::stol(s,0,15);
std::cout<< s<<" in base 15: "<<n<<std::endl;
// -> 1023456789ABCDE in base 15: 29480883458974409
}
pow(base, i) uses floating point and so you loose some precision on some numbers.
Exceeded double precision.
Precision of double, the return value from pow(), is precise for at least DBL_DIG significant decimal digits. DBL_DIG is at least 10 and typically is 15 IEEE 754 double-precision binary.
The desired number 29480883458974409 is 17 digits, so some calculation error should be expected.
In particular, sum += pow(base,i)*value[14-i] is done as a long long = long long + (double * long long) which results in long long = double. The nearest double to 29480883458974409 is 29480883458974408. So it is not an imprecise value from pow() that causes the issue here, but an imprecise sum from the addition.
#Mooing Duck in a comment references code to avoid using pow() and its double limitation`. Following is a slight variant.
unsigned long long ullongpow(unsigned value, unsigned exp) {
unsigned long long result = !!value;
while (exp-- > 0) {
result *= value;
}
return result;
}
I am trying to manipulate 64 bits. I use the number to store in an unsigned long long int.To test the porcess I ran the following program
#include <iostream>
using namespace std;
int main()
{
unsigned long long x = 1;
int cnt = 0;
for(int i =0 ;i<64;++i)
{
if((1<<i)&x)
++cnt;
}
cout<<cnt;
}
but the output of the cnt is 2 which is clearly wrong. How Do I manipulate 64 bits? where is the correction? Actually I am trying to find parity, that is number of 1's in binary representation of a number less than 2^63.
For it's 64-bit, you should use a 64-bit 1. So, try this:
if(((unsigned long long) 1<<i)&x)
(1<<i) will overflow when i greater than 32
you can write the condition like (x >> i) & 1
What is meant by manipulation in your case? I am thinking you are going to test each and every bit of variable x. Your x should contain maximum value because you are going to test every bit of your variable x
int main()
{
unsigned long long x = 0xFFFFFFFFFFFFFFFF;
int cnt = 0;
for(int i =0 ;i<64;++i)
{
if((1<<i)&x)
++cnt;
}
cout<<cnt;
}