Last digit of partial sum of Fibonacci series - c++

I'm trying to find the last digit of the sum of the fibonacci series from a starting to an end point. As we find the last digit using %10 , Fibonnaci will repeat it's last digit sequence every 60 times - using the Pisano Series
My attempt at the solution:
We find the last digits of the first 60 digits, store them in an array and then continuously loop over and sum over the digits starting from n%60 to m. We then finally modulo 10 the result.
#include <iostream>
#include <vector>
using std::vector;
int fibonacci_fast(long long n,long long m) {
// write your code here
long long a[60];
a[0]=0;
a[1]=1;
long long sum=0;
for(long long i=2;i<60;i++)
{
a[i] = a[i-1]+a[i-2];
a[i] = a[i] % 10;
}
int j=0;
int p=1;
int c=0;
for(int i=n%60;;i++)
{
if(i==60)
{
i=i%60;
}
sum=sum+a[i];
c=c+1;
if(c==m)
{
break;
}
}
return sum%10;
}
int main() {
long long from, to;
std::cin >> from >> to;
std::cout << fibonacci_fast(from, to) << '\n';
}
The major issue I'm having with this current code is that for lower values, it works fine, but if I input higher values such as 0 to 239, It only works when the condition changes to if(c+1)==m which then results in the smaller values solutions turning wrong.
The c counter works correctly though and goes up to 239 but I still cannot figure out the issue with the code.

#include <vector>
using std::vector;
int fibonacci_fast(long long n,long long m) {
// write your code here
long long a[60];
a[0]=0;
a[1]=1;
long long sum=0;
sum = a[0] + a[1];
for(long long i=2;i<60;i++)
{
a[i] = a[i-1]+a[i-2];
a[i] = a[i] % 10;
sum = (sum + a[i]) % 10;
}
int x = (m - n + 1)/60;
sum = (sum * x) % 10;
int i = n + 60 * x;
while(i <= m)
{
sum = (sum + a[i%60]) % 10;
i++;
}
return sum;
}
int main() {
long long from, to;
std::cin >> from >> to;
std::cout << fibonacci_fast(from, to) << '\n';
}

I think you need to set the variable c to be equal to the value of n and not 0 (zero)
int c = n;
Also, please clear the concept whether you want to include the index m or not.
Example, if user enters:
n -> 10
m -> 20
Then your code provided above will add the last digit values of the Fibonacci numbers from the index 10 to the index 19 only. So please clear this doubt of mine, then I will add further.

Related

Unable to have 100 factorial with C++ on output screen(displaying 0)

Well I am stuck on this problem for quite a while:
Question:
You are asked to calculate factorials of some small positive integers.
Input:
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output:
For each integer n given at input, display a line with the value of n!
//coded in c++
#include <bits/stdc++.h> //loadind up all the libraries at once.
using namespace std;
int main()
{ int T;
scanf("%d", &T);
//I am not doing "cin<<" cause "scanf" is faster than it
for (int i = 0; i < T; i++)
{
int N;
scanf("%d",&N);
long long int product = 1;
while (N >0){
product = product * N;
N--;
}
printf("%lld\n",product);
}
return 0;
}
I am able to get 10!,20! but unable to get 100! (factorial)
so the extreme case doesn't satisfy. Please help me to get a good data type for my variable as 100! a factorial has over than 100 digits. It is displaying 0 when I input 100 on the terminal.
P.S - This problem is from CodeChef website (FCTRL2).
A 64bit integer will overflow with 23!
Therefore you need to do it with digits and a vector.
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 23!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Using a bigint library will be much faster.
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17

Comparing digits in number

Consistently comparing digits symmetrically to its middle digit. If first number is bigger than the last , first is wining and I have to display it else I display last and that keep until I reach middle digit(this is if I have odd number of digits), if digit don't have anything to be compared with it wins automatically.
For example number is 13257 the answer is 7 5 2.
Another one 583241 the answer is 5 8 3.
For now I am only trying to catch when number of digits is odd. And got stuck.. This is my code. The problem is that this code don't display any numbers, but it compares them in the if statement(I checked while debugging).
#include <iostream>
using namespace std;
int countDigit(int n) {
int count = 0;
while (n != 0) {
count++;
n /= 10;
}
return count;
}
int main() {
int n;
cin >> n;
int middle;
int count = countDigit(n);
if (count % 2 == 0) {
cout<<"No mid digit exsist!!";
}
else {
int lastDigit = n % 10;
middle = (count + 1) / 2;
for (int i = 0; i < middle; i++) {
for (int j = lastDigit; j<middle; j--) {
if (i > j) {
cout << i <<' ';
}
else {
cout << j;
}
}
}
}
return 0;
}
An easier approach towards this, in my opinion, would be using strings. You can check the size of the string. If there are even number of characters, you can just compare the first half characters, with the last half. If there are odd numbers, then do the same just print the middle character.
Here's what I'd do for odd number of digits:
string n;
cin>>n;
int i,j;
for(i=0,j=n.size()-1;i<n.size()/2,j>=(n.size()+1)/2;i++,j--)
{
if(n[i]>n[j]) cout<<n[i]<<" ";
else cout<<n[j]<<" ";
}
cout<<n[n.size()/2]<<endl;
We analyze the requirements and then come up with a design.
If we have a number, consisting of digits, we want to compare "left" values with "right" values. So, start somehow at the left and the right index of digits in a number.
Look at this number: 123456789
Index: 012345678
Length: 9
in C and C++ indices start with 0.
So, what will we do?
Compare index 0 with index 8
Compare index 1 with index 7
Compare index 2 with index 6
Compare index 3 with index 5
Compare index 4 with index 4
So, the index from the left is running up and the index from the right is running down.
We continue as long as the left index is less than or equal the right index. All this can be done in a for or while loop.
It does not matter, wether the number of digits is odd or even.
Of course we also do need functions that return the length of a number and a digit of the number at a given position. But I see that you know already how to write these functions. So, I will not explain it further here.
I show you 3 different examples.
Ultra simple and very verbose. Very inefficient, because we do not have arrays.
Still simple, but more compressed. Very inefficient, because we do not have arrays.
C++ solution, not allowed in your case
Verbose
#include <iostream>
// Get the length of a number
unsigned int length(unsigned long long number) {
unsigned int length = 0;
while (number != 0) {
number /= 10;
++length;
}
return length;
}
// Get a digit at a given index of a number
unsigned int digitAt(unsigned int index, unsigned long long number) {
index = length(number) - index - 1;
unsigned int result = 0;
unsigned int count = 0;
while ((number != 0) && (count <= index)) {
result = number % 10;
number /= 10;
++count;
}
return result;
}
// Test
int main() {
unsigned long long number;
if (std::cin >> number) {
unsigned int indexLeft = 0;
unsigned int indexRight = length(number) - 1;
while (indexLeft <= indexRight) {
if (digitAt(indexLeft, number) > digitAt(indexRight, number)) {
std::cout << digitAt(indexLeft, number);
}
else {
std::cout << digitAt(indexRight, number);
}
++indexLeft;
--indexRight;
}
}
}
Compressed
#include <iostream>
// Get the length of a number
size_t length(unsigned long long number) {
size_t length{};
for (; number; number /= 10) ++length;
return length;
}
// Get a digit at a given index of a number
unsigned int digitAt(size_t index, unsigned long long number) {
index = length(number) - index - 1;
unsigned int result{}, count{};
for (; number and count <= index; ++count, number /= 10)
result = number % 10;
return result;
}
// Test
int main() {
if (unsigned long long number; std::cin >> number) {
// Iterate from left and right at the same time
for (size_t indexLeft{}, indexRight{ length(number) - 1 }; indexLeft <= indexRight; ++indexLeft, --indexRight)
std::cout << ((digitAt(indexLeft,number) > digitAt(indexRight, number)) ? digitAt(indexLeft, number) : digitAt(indexRight, number));
}
}
More modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
if (std::string numberAsString{}; std::getline(std::cin, numberAsString) and not numberAsString.empty() and
std::all_of(numberAsString.begin(), numberAsString.end(), std::isdigit)) {
for (size_t indexLeft{}, indexRight{ numberAsString.length() - 1 }; indexLeft <= indexRight; ++indexLeft, --indexRight)
std::cout << ((numberAsString[indexLeft] > numberAsString[indexRight]) ? numberAsString[indexLeft] : numberAsString[indexRight]);
}
}
You are trying to do something confusing with nested for-cycles. This is obviously wrong, because there is nothing “quadratic” (with respect to the number of digits) in the entire task. Also, your code doesn’t seem to contain anything that would determine the highest-order digit.
I would suggest that you start with something very simple: string’ify the number and then iterate over the digits in the string. This is obviously neither elegant nor particularly fast, but it will be a working solution to start with and you can improve it later.
BTW, the sooner you get out of the bad habit of using namespace std; the better. It is an antipattern, please avoid it.
Side note: There is no need to treat odd and even numbers of digits differently. Just let the algorithm compare the middle digit (if it exists) against itself and select it; no big deal. It is a tiny efficiency drawback in exchange for a big code simplicity benefit.
#include <cstdint>
#include <iostream>
#include <string>
using std::size_t;
using std::uint64_t;
uint64_t extract_digits(uint64_t source) {
const std::string digits{std::to_string(source)};
auto i = digits.begin();
auto j = digits.rbegin();
const auto iend = i + (digits.size() + 1) / 2;
uint64_t result{0};
for (; i < iend; ++i, ++j) {
result *= 10;
result += (*i > *j ? *i : *j) - '0';
}
return result;
}
int main() {
uint64_t n;
std::cin >> n;
std::cout << extract_digits(n) << std::endl;
}
If the task disallows the use of strings and arrays, you could try using pure arithmetics by constructing a “digit-inverted” version of the number and then iterating over both numbers using division and modulo. This will (still) have obvious limitations that stem from the data type size, some numbers cannot be inverted properly etc. (Use GNU MP for unlimited integers.)
#include <cstdint>
#include <iostream>
using std::size_t;
using std::uint64_t;
uint64_t extract_digits(uint64_t source) {
uint64_t inverted{0};
size_t count{0};
for (uint64_t div = source; div; div /= 10) {
inverted *= 10;
inverted += div % 10;
++count;
}
count += 1;
count /= 2;
uint64_t result{0};
if (count) for(;;) {
const uint64_t a{source % 10}, b{inverted % 10};
result *= 10;
result += a > b ? a : b;
if (!--count) break;
source /= 10;
inverted /= 10;
}
return result;
}
int main() {
uint64_t n;
std::cin >> n;
std::cout << extract_digits(n) << std::endl;
}
Last but not least, I would strongly suggest that you ask questions after you have something buildable and runnable. Having homework solved by someone else defeats the homework’s purpose.

How to print the b-th prime number coming after n?

I'm trying to write a c++ program which gets an integer n (n>=1 && n<=100000) from the user and puts the sum of its digits into b. The output needed is the b-th prime number coming after n. I'm an absolute beginner in programming so I don't know what's wrong with the for loop or any other code that it doesn't show the correct output. For example the 3rd prime number after 12 (1+2=3) is 19 but the loop counts the prime numbers from 2 instead of 12, so it prints 7 as result.
#include <iostream>
using namespace std;
bool isPrime(int n)
{
if(n <= 1)
return false;
for(int i = 2; i <= (n/2); i++)
if(n % i == 0)
return false;
return true;
}
int main()
{
long int n;
int b = 0;
cin>>n;
while(n >= 1 && n <= 100000){
b += n % 10;
n /= 10;
}
for(int i = n, counter = b; counter <= 10; i++)
if(isPrime(i)){
counter++;
if(i > n)
cout<<counter<<"th prime number after n is : "<<i<<endl;
}
return 0;
}
So one of the possible solutions to my question, according to #Bob__ answer (and converting it to the code style I've used in the initial code) is as follows:
#include <iostream>
using namespace std;
bool isPrime(long int number)
{
if(number <= 1)
return false;
for(int i = 2; i <= (number / 2); i++)
if(number % i == 0)
return false;
return true;
}
int sumOfDigits(long int number)
{
int sum = 0;
while(number >= 1 && number <= 100000)
{
sum += number % 10;
number /= 10;
}
return sum;
}
long int bthPrimeAfter(int counter, long int number)
{
while(counter)
{
++number;
if(isPrime(number))
--counter;
}
return number;
}
int main()
{
long int number;
cin>>number;
int const counter = sumOfDigits(number);
cout<<bthPrimeAfter(counter, number)<<"\n";
return 0;
}
As dratenik said in their comment:
You have destroyed the value in n to produce b in the while loop. When the for loop comes around, n keeps being zero.
That's a key point to understand, sometimes we need to make a copy of a variable. One way to do that is passing it to a function by value. The function argument will be a local copy which can be changed without affecting the original one.
As an example, the main function could be written like the following:
#include <iostream>
bool is_prime(long int number);
// ^^^^^^^^ So is `n` in the OP's `main`
int sum_of_digits(long int number);
// ^^^^^^^^^^^^^^^ This is a local copy.
long int nth_prime_after(int counter, long int number);
int main()
{
long int number;
// The input validation (check if it's a number and if it's in the valid range,
// deal with errors) is left to the reader as an exercise.
std::cin >> number;
int const counter = sum_of_digits(number);
std::cout << nth_prime_after(counter, number) << '\n';
return 0;
}
The definition of sum_of_digits is straightforward.
int sum_of_digits(long int number)
{
int sum = 0;
while ( number ) // Stops when number is zero. The condition n <= 100000
{ // belongs to input validation, like n >= 0.
sum += number % 10;
number /= 10; // <- This changes only the local copy.
}
return sum;
}
About the last part (finding the nth prime after the chosen number), I'm not sure to understand what the asker is trying to do, but even if n had the correct value, for(int i = n, counter = b; counter <= 10; i++) would be just wrong. For starters, there's no reason for the condition count <= 10 or at least none that I can think of.
I'd write something like this:
long int nth_prime_after(int counter, long int number)
{
while ( counter )
{
++number;
if ( is_prime(number) )
{
--counter; // The primes aren't printed here, not even the nth.
}
}
return number; // Just return it, the printing is another function's
} // responsabilty.
A lot more could be said about the is_prime function and the overall (lack of) efficiency of this algorithm, but IMHO, it's beyond the scope of this answer.

How do i determine the first digit of a number without knowing the number of digits?c++

For example, 42556. How do I determine first digit if I don't know the number of digits in the number? I could't find an algorithm that suits me anywere! (I mean to determine the 4 in 42556)
Assuming a is the input number.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
long a = 42556;
long num;
num=floor(log10(a))+1;
//cout<<num<<" "<<"\n"; //prints the number of digits in the number
cout<<a/(int)pow(10,num-1)<<"\n"; //prints the first digit
cout<<a%10<<"\n"; //prints the last digit
return 0;
}
Live demo here.
You could keep on dividing it by 10 until you've reached the last digit:
int lastDigit(int n) {
n = abs(n); // Handle negative numbers
int ret = n;
while (n > 0) {
ret = n % 10;
n /= 10;
}
return ret;
}
Iteratively divide by 10 until the result is less than 10.
num = 42556
while num > 9
num = num / 10
All answers assumed you have an integer number. But generally, you can first get the integer form using the function floor from <cmath>, i.e.
#include <cmath>
int getlastdigit(double number)
{
long long n = (long long)floor(number);
while(n > 9)
n /= 10;
return n;
}
Try this:
int firstdigit(int n) {
int x = n;
while(n != 0) {
x = n%10;
n = n/10;
}
return x;
}

Multi threading program to count the frequency of prime numbers giving inaccurate results.

I am working on a assignment where I need to calculate the frequency of prime numbers from 1 to 10 million. we are to do this by taking variable U (which is 10 million) and dividing it into N parts and have multiple threads calculate the frequency of prime numbers, we must try this with different values for N and observe our processor ticks and time taken to calculate. The way the program works is 10 million is divided into N parts, upper and lower bounds are put into a vector of threads and each thread calls a function which counts the prime numbers.
now the frequency of primes from 1-million should be 664579. i am getting slightly inaccurate results when doing multiple threads. for example if i run the program with N=1, meaning only one thread will solve i get a frequency of 6645780, which is off by 1. N=2 i get the correct result of 664579, N=3 freq=664578, and so on. below is the code, any help is greatly appreciated.
#include <iostream>
#include <thread>
#include <vector>
#include<algorithm>
#define MILLION 1000000
using namespace std;
using std::for_each;
void frequencyOfPrimes(long long upper, long long lower, long long* freq)
{
long long i, j;
if (lower == 2) { *freq = upper; }
else { *freq = upper - lower; }
for (i = lower; i <= upper; ++i)
for (j = (long long)sqrt(i); j>1; --j)
if (i%j == 0) { --(*freq); break; }
return;
}
int main(int argc, char* argv[])
{
clock_t ticks = clock();
long long N = 10; //declare and initialize number of threads to calculate primes
long long U = 10*MILLION;
long long F=0; //total frequency
long long d = U / N; // the quotient of 10mil/number of threads
vector<thread> tV; //declare thread vector
vector<long long> f, u, l; //vector for freq, upper and lower bounds
f.resize(N);//initialize f
for (long long i = 0; i<N; i++) { //initialize and populate vectors for upper and lower bounds
if (i == 0) {
l.push_back(2);
u.push_back(d);
}
else {
l.push_back(u.at(i-1)+ 1);
u.push_back(u.at(i-1) + d);
}
}
u.at(N-1) = U; //make sure last thread has value of U for upper bound
for (long long i = 0; i < N; i++) { //initialize thread vectors
tV.push_back(thread(frequencyOfPrimes, u.at(i), l.at(i), &f.at(i)));
}
for_each(tV.begin(), tV.end(), mem_fn(&thread::join));
ticks = clock() - ticks;
for (long long i = 0; i < N; i++)
F = f.at(i) + F;
cout << "Frequency is " << F << endl;
cout << "It took " << ticks << " ticks (";
cout << ((float)ticks) / CLOCKS_PER_SEC << " seconds)" << endl;
this_thread::sleep_for(chrono::seconds(5));
return 0;
}
This has nothing to do with multi threading. Always test your functions:
#include <iostream>
#include <cmath>
using namespace std;
// this is your function with a shorter name
void fop_strange(long long upper, long long lower, long long* freq)
{
long long i, j;
if (lower == 2) { *freq = upper; }
else { *freq = upper - lower; }
for (i = lower; i <= upper; ++i)
for (j = (long long)sqrt(i); j>1; --j)
if (i%j == 0) { --(*freq); break; }
return;
}
// attention, I switched order of upper and lower
long long fop(long long a, long long b) {
long long f = 0;
fop_strange (b, a, &f);
return f;
}
int main() {
cout << fop(2, 4) << endl;
cout << fop(10, 14) << endl;
return 0;
}
Let's first count the primes manually:
2 to 4 (inclusive) => 2 (2, 3)
10 to 14 (inclusive) => 2 (11, 13)
Now your function (live on ideone)
3
1
Why? Well, you're correctly decreasing the count when you encounter a non prime, but you don't initialise it correctly. The range from 2 to 4 inclusive has 3 numbers, not 4. The range from 2 to 1 million has 1 million - 2 + 1, not 1 million numbers. The range from 10 to 14 inclusive has 5 numbers, not only 4. Etc.
This explains the results you're getting: For a range that starts from 2 your function returns 1 number more, fit every other range 1 number less. Therefore, when using only one thread and thus only a single range starting with 2 your result is one more, and every thread you add adds a range that brings one less, thus decreasing the overall result by one.