I made a function to double every other digit of a number, but for some reason it converts the in to hex before returning. I checked, and that hex is accurate to an actual number, but how do I get it to stop returning hex? Here's the code.
unsigned long long* Luhn_Algorigthem::double_every_other_value(unsigned long long int in) {
unsigned long long int* out = new unsigned long long;
int counter = 10;
for (int i = 0; i < std::to_string(in).length(); i++) {
if (i % 2 == 0) { //Is even
counter * 10;
out += (unsigned long long)((in % counter) * 2);
}
else { //Is odd
out += (unsigned long long)(std::to_string(in).at(i));
}
}
doubled_val = (unsigned long long)out;
return (unsigned long long*)33;
delete out;
}
Unsigned and long are type modifiers (like adjectives without a noun), have you tried unsigned long int for explicit type casting?
#TheUndedFish helped solve the problem for me, I ended up just getting rid of the pointer, and used the doubled val variable for it instead without allocating memory to the heap. This is the updated code:
unsigned long long int Luhn_Algorigthem::double_every_other_value(unsigned long long int in) {
//unsigned long long int* out = new unsigned long long;
int counter = 10;
for (int i = 0; i < std::to_string(in).length(); i++) {
if (i % 2 == 0) { //Is even
counter * 10;
doubled_val += (in % counter) * 2;
}
else { //Is odd
doubled_val += std::to_string(in).at(i);
}
}
//delete out;
return doubled_val;
}
How to find count of numbers between a and b (inclusive) which contains 0 as their digit. I am not able to get this with the idea which i have used below in my code, it becomes very complex in case of leading zeroes
for ex if a=1 and b=200 total number should be 29 but i am getting 39.
Can anyone suggest an efficient way of doing it?
constraints:
1<=a<=b<=10^17
code:
long long int F(long long int dig, long long int a, long long int num)
{
if(dig == 0) {
if(a>0)
return 1;
else
return 0;
}
if(mem[dig][a])
return D[dig][a];
mem[dig][a] = 1;
long long int ret = 0;
for(long long int i = 0;i<=9;i++) {
if(i==num)
ret=(ret+F(dig-1,a+1,num));
else
ret=(ret+F(dig-1,a,num));
}
D[dig][a] = ret;
return ret;
}
long long int solve(long long int x,long long int num)
{
char cad[100];
long long int ret = 0;
long long int a=0,b=0,c=0,j;
sprintf(cad,"%lld",x);
int len = strlen(cad);
long long int qued = len;
for(long long int i = 0;i < len;i++) {
qued--;
long long int d = cad[i] - '0';
for(j=0;j <d;j++) {
if(j==num) {
if(num==0 && i==0)
a=a+0;
else
a=a+1;
ret=(ret+F(qued,a,num));
}
else
ret=(ret+F(qued,a,num));
}
if(d==num)
a=a+1;
}
return ret;
}
solution is -> solve(b+1,0)-solve(a,0)
but i am getting wrong answer with this
the link from which i got the above idea is http://codeforces.com/blog/entry/8221
A Simple way to do it would be:
inList = [1, 2, ... n]
outList = []
for i in inList:
for j in len(i):
if i%10 || i==0:
//there is a 0
outList.add(i)
break;
if(i<10)
//i cannot contain a 0
break;
i=i/10
Probibly only works with positive ints, but its trivial to account for negitive numbers.
Simple and efficient O(10N) or O(17N) according to your constraints
I'm creating a bit array using unsigned chars for an assignment in my object oriented programming course. I was given the basic layout of what function we need. One was our Query function which is const.
this is my member data:
unsigned char* barray; // pointer to the bit array
unsigned int arraySize;
static const unsigned int charSize = (sizeof(unsigned char) * 8);
and this is the function I'm having issues with:
bool BitArray::Query(unsigned int index)const{
unsigned int i = (Index(index)),
p = Position(index);
unsigned int check = 1;
check = Move(check, p);
if ((check & barray[i]) == 0)
return false;
else
return true;
}
This function as well as an operator<< overload (also uses const keyword) get pissed off at me when I use my other functions in them (Index, Position, Move).
"IntelliSense: the object has type qualifiers that are not compatible with the member function "BitArray::Index" object type is const BitArray"
What is going on?
/* determine which element in array of chars to use */
unsigned int BitArray::Index(unsigned int n){
unsigned int index = (n / charSize);
if (((n % charSize) == 0) && (index < 0)){
index -= 1;
}
return index;
}
/* determine index of bit of the particular char */
unsigned int BitArray::Position(unsigned int n){
unsigned int position = n;
position -= ((n / charSize) * charSize);
if (position == 0)
position = charSize - 1;
else
position--;
return position;
}
unsigned int BitArray::Move(unsigned int n, unsigned int m){
return n << m;
}
Using Microsoft Visual Studio Express 2013
Those other functions need to be marked const as well. If they're not const, then you have no business calling them from a const function.
You can find the problem statement here.
My solution can be found here. I am getting correct answers for the test cases but the judge is indicating all answers wrong. What is wrong with my code?
#include <iostream>
#include <vector>
#include <map>
#include <math.h>
using namespace std;
map<long long,long long> arr;
void preProcess();
long long powerOfThree(long long num);
long long powerOfTwo(long long num);
long long theta(long long num);
int main()
{
preProcess();
long long t,k;
cin>>t;
while(t--)
{
cin>>k;
cout<<theta(k)<<endl;
}
}
void preProcess()
{
arr.insert(pair<long long,long long>(0,0));//arr[0]=0;
arr.insert(pair<long long,long long>(1,0));//arr[1]=0;
arr.insert(pair<long long,long long>(2,1));//arr[2]=1;
arr.insert(pair<long long,long long>(3,1));//arr[3]=1;
//arr.insert(pair<long long,long long>(4,2));//arr[4]=2;
//arr.insert(pair<long long,long long>(5,3));//arr[5]=3;
}
long long powerOfTwo(long long num)
{
long long ret=0;
while(num%2==0)
{
ret++;
num = num/2;
}
return ret;
}
long long theta(long long num)
{
long long ret;
map<long long,long long>::iterator it = arr.find(num);
if(it != arr.end())
{
return arr[num];
}
else
{
if(num%2==0)
{
long long a = powerOfTwo(num);
long long q = (num/(long long)pow(2,a));
ret = a + theta(q);
}
else if(num%3==0)
{
long long a = powerOfThree(num);
long long q = (num/(long long)pow(3,a));
ret = a + theta(q);
}
else
{
ret = 1 + theta(num-1);
}
}
arr.insert(pair<long long,long long>(num,ret));//arr[num]=ret;
return ret;
}
long long powerOfThree(long long num)
{
long long ret=0;
while(num%3==0)
{
ret++;
num = num/3;
}
return ret;
}
My approach is to first count all the powers of 2 and 3 in number and then reduce the result by 1. Again repeat the process till it is 1.
your method will fail in a number say for eg (2^8 + 1) *3^2. There would infact be many such numbers.
I would give a solution in Python(bcoz thats what I am comfortable in):
step = [0,0,1,1]
def find(a):
global step
t = len(step)
for n in range(t,a+1):
if ((n%3 == 0) and (n%2 == 0)):
step.append( 1 + min(step[n-1],step[n/2],step[n/3]))
elif (n%2==0):
step.append( 1 + min(step[n-1],step[n/2]))
elif (n%3 == 0) :
step.append( 1 + min(step[n-1],step[n/3]))
else :
step.append( 1 + step[n-1])
return step[a]
n = int(raw_input())
arr = []
for a in range(0,n):
arr.append(raw_input())
for st in arr:
n = int(st)
print find(n)
I was doing this problem called arithmetic progression on Hackerrank.
https://www.hackerrank.com/challenges/arithmetic-progressions
My solution passed all first six tests. I have tried every possible way of optimizing my code, including caching, more efficient operation. I still could not pass the test. The two places I think I failed is factorial function and pow function.
Basically, I used unordered_map to store all of the previous results. If the argument is one of the key, I will just returned the result right away.
Here is my code:
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <utility>
#include <ctime>
#include <sys/time.h>
using namespace std;
#define mod(m) (m > 1000003) ? m % 1000003 : m
//used for hashing the pair
namespace std {
template<typename a, typename b>
struct hash< pair<a, b> > {
private:
const hash<a> ah;
const hash<b> bh;
public:
hash() : ah(), bh() {};
size_t operator()(const std::pair<a, b> &p) const {
return ah(p.first) ^ bh(p.second);
}
};
} // namespaces
//the code below is used for collecting statistics
/*
typedef unsigned long long timestamp_t;
static timestamp_t get_timestamp ()
{
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}
*/
//note that the number could get really large, that's why I use unsigned long long for most of data type
static unsigned long long cache_D[100000];
static unsigned long long cache_d[100000];
static unsigned long long cache_p[100000];
static unordered_map<unsigned long long, unsigned long long> cache_F; //use unordered_map to store the factorial, avg insert, lookup O(1)
static unordered_map<pair<unsigned long long, unsigned long long>, unsigned long long> cache_P; //use unordered_map to store the pow
//static double pow_sec = 0;
//static double fac_sec = 0;
/**
* Use the fast pow algorithm. On top of that, I add caching (stored in unordered map) to speed up the pow
* #param x base
* #param y exponent
* #return x ^ y
*/
unsigned long long pow(unsigned long long x, unsigned long long y)
{
//timestamp_t t0 = get_timestamp();
pair<unsigned long long, unsigned long long> curr(x, y);
if(cache_P.find(curr) != cache_P.end())
{
//timestamp_t t1 = get_timestamp();
//pow_sec += (t1 - t0) / 1000000.0L;
return cache_P[curr];
}
unsigned long long result = 1;
unsigned long long mod_x = mod(x);
//unsigned long long count = 0;
while( y )
{
if ( y & 1 )
{
unsigned long long temp = result * mod_x;
result = mod(temp);
}
y >>= 1;
unsigned long long temp = mod_x * mod_x;
mod_x = mod(temp);
}
cache_P[curr] = result;
//timestamp_t t1 = get_timestamp();
//pow_sec += (t1 - t0) / 1000000.0L;
return result;
}
/**
* same idea as pow, caching whenever I can
* #param x number to be factorialized
* #return x!
*/
unsigned long long factorial(unsigned long long x)
{
//timestamp_t t0 = get_timestamp();
if (cache_F.find(x) != cache_F.end())
{
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return cache_F[x];
}
else
{
unsigned long long result = 1;
//here we go from x to 1 since we could speed up operation as soon as we have x - 1 or x - 2 or x - 3 in our caching (just x * (x - 1)! )
for(unsigned long long i = x; i >= 1; i--)
{
if(cache_F.find(i) != cache_F.end())
{
unsigned long long temp1 = result * cache_F[i];
result = mod(temp1);
cache_F[x] = result;
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return result;
}
unsigned long long mod_i = mod(i);
unsigned long long temp2 = result * mod_i;
result = mod(temp2);
}
cache_F[x] = result;
//timestamp_t t1 = get_timestamp();
//fac_sec += (t1 - t0) / 1000000.0L;
return result;
}
}
void query(int from, int to)
{
unsigned long long k = 0;
unsigned long long constant = 1;
for(int i = from - 1; i < to; i++)
{
k += cache_p[i];
unsigned long long temp = constant * cache_D[i];
constant = mod(temp);
}
unsigned long long temp = constant * factorial(k);
constant = mod(temp);
printf("%llu %llu\n", k, constant);
}
void update(int from, int to, int how_much)
{
for(int i = from - 1; i < to; i++)
{
cache_p[i] += how_much;
unsigned long long temp = cache_D[i] * pow(cache_d[i], (unsigned long long)how_much);
cache_D[i] = mod(temp);
}
}
int main() {
int num_vec, num_operations;
FILE *pFile = fopen("input.txt", "r");
fscanf(pFile, "%d", &num_vec);
for(int i = 0; i < num_vec; i++)
{
unsigned long long a, d, q;
fscanf(pFile, "%llu %llu %llu", &a, &d, &q);
cache_d[i] = d;
cache_p[i] = q;
cache_D[i] = pow(d, q);
}
fscanf(pFile, "%d", &num_operations);
for(int i = 0; i < num_operations; i++)
{
int what_operation, from, to;
fscanf(pFile, "%d %d %d", &what_operation, &from, &to);
if(what_operation == 0)
{
query(from, to);
}
else if (what_operation == 1)
{
int add_q;
fscanf(pFile, "%d", &add_q);
update(from, to, add_q);
}
}
printf("sec for pow: %f\n sec for fac: %f", pow_sec, fac_sec);
return 0;
}
It would be really helpful if anyone knows how to further optimize my code. Thanks!
Regarding Factorial.
"unsigned long long" has a range from 0 to
18,446,744,073,709,551,615
the factorial of 21 is:
51,090,942,171,709,440,000
So, this means your function can only return the correct results for factorial of 0 through 20.
It will be a lot easier to start with a pre-built cache with 21 elements (zero through 20).
unsigned long long fact_cache [21] = {
1 ,
1 ,
2 ,
6 ,
24 ,
120 ,
720 ,
5040 ,
40320 ,
362880 ,
3628800 ,
39916800 ,
479001600 ,
6227020800 ,
87178291200 ,
1307674368000 ,
20922789888000 ,
355687428096000 ,
6402373705728000 ,
121645100408832000 ,
2432902008176640000
};
Now your factorial function can just look up the right value in the array (checking bounds if you like).
edit: (Realized the OP intended 'factorial mod 1000003")
I started by reading the answers to:
Fast way to calculate n! mod m where m is prime?
Based on the second answer, with code examples in python, and more information here:
http://www.algorithmist.com/index.php/Modular_inverse
He gave this Python code, as well as a possible improvement.
def factorialMod(n, modulus):
ans=1
if n <= modulus//2:
#calculate the factorial normally (right argument of range() is exclusive)
for i in range(1,n+1):
ans = (ans * i) % modulus
else:
#Fancypants method for large n
for i in range(n+1,modulus):
ans = (ans * i) % modulus
ans = modinv(ans, modulus)
ans = -1*ans + modulus
return ans % modulus
This has some advantages, over the original method when n is larger than the modulus divided by 2, since we can reduce the number of multiplications by solving for the modular inverse.
Because we know the modulus (1000003), we can solve for the modinv by using its totient (1000002).
In pseudo-code we get something like:
long factorial_mod( long n ) {
if( n > 1000003 )
return 0; //from Thomas's comment
if( cache[n] != 0 ) //if the cache has the answer
return cache[n];
long result = 1;
if ( n <= 500001 )
{
for( long i = 1; i <= n; i++ )
{
result = (result * i) % 1000003;
cache[i] = result;
}
}
else
{
for( long i = n+1; i <= 1000003; i++)
{
result = (result * i) % 1000003;
}
result = modinv(result, 1000003);
result = -1*result + 1000003;
}
result = result % 1000003;
cache[n] = result;
return result;
}
long modinv( long a, int modulus ) {
return modPow( a, 1000002, modulus); // ( (a to the totient) mod the modulus )
}
If we didn't want to compute the totient, we could have used extended euler GCD to solve for the modular inverse. (of course the totient of primes is very easy to compute...just subtract one).