I'm trying to make this code run faster, and I am having trouble doing so. I can pass most of my test cases, but as the numbers get larger I cant pass them.
Input: 92871036442 3363728910382456 output: 1160053175781729
Input: 1 1000000000000000000 output: 264160473575034274
These test cases won't pass. What can I do to speed up my algorithm and prevent it from timing out?
#include<iostream>
using namespace std;
bool isLuckyNumber(unsigned long long n)
{
bool found6 = false, found8 = false;
while (n > 0)
{
int digit = n % 10;
if (digit == 6)
{
found6 = true;
}
else if (digit == 8)
{
found8 = true;
}
//removing last digit
n = n / 10;
}
if (found6 && found8)
{
return false;
}
//otherwise if any one of them is true, it is a lucky number
else if (found6 || found8)
{
return true;
}
//otherwise not a lucky number
return false;
}
int main()
{
//creating needed variables, using unsigned long long as data type as it
//can store huge values (between 0 and 18446744073709551615)
unsigned long long L, R, count = 0;
//reading L and R
cin >> L >> R;
//looping as long as L<=R
while (L <= R)
{
//if L is lucky number, incrementing count
if (isLuckyNumber(L))
{
count++;
}
//incrementing L
L++;
}
//displaying count at the end
cout << count << endl;
return 0;
}