Check if number is automorphic - c++

I'm getting two numbers. First natural number n and second n - digit number. n range is 1<=n<=50000. The problem is how can I do n * n on big numbers with for example 49000 digits. I was trying to do it on string, then I have array with each digit but what then? Write function that multiply n * n as string? I didn't have idea how to start it. Any ideas?
EDIT
I check if number is automorphic but how to edit it to work with numbers to 50000 digits?
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
unsigned int n, m = 10, a, b;
cin >> n;
b = m;
while (n > b) {
b *= m;
}
a = (n * n) % b;
if (a == n)
cout << "OK";
else
cout << "NO";
return 0;
}

They're various ways of dealing with big int in C++
Using a library, like boost::xint, Matt McCutchen bigint, InfInt, etc...
Doing the needed operation by hand (if they're not much operations needed, you could implemented), in this case you only need multiplication (the module is with a power of 10 and can easily implemented), you could use for example std::vector<unsigned char> to store the digits of n and do the multiplication as teach in school, digit by digit, and report the last digits needed.
Note: you could do only part of the multiplication for obtaining the last digits needed (by take care with how much you need, for the digits needed). For 5000 digits, doing all the multiplication would finish lightning fast.

Related

Program Last Digit of a Large Fibonacci Number for n-th Fibonacci number. C++

I'm trying to solve Fibonacci using C++, but my code shows negative numbers when the output digit limit crosses with big numbers.
#include<stdio.h>
#include<iostream>
using namespace std;
int64_t get_fibonacci_last_digit_naive(int n)
{
int64_t a = 0, c, i;
int64_t b = 1;
if (n == 0)
return (a);
for (i = 2; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return (b);
}
int main()
{
int n;
cin >> n;
cout << get_fibonacci_last_digit_naive(n) << '\n';
return 0;
}
so when my input is 239, my out put shows
239
-1716907696316940191
Process returned 0 (0x0) execution time : 12.395 s
Press any key to continue.
Now how i can store digits with no upper limits in C++?. i am very noob and exlpain me thinking that i dont know anythg. so huw can i print digits more than 30 in c++?
The built-in integer data types in C++ can only store values in a given range. For int64 that would be -263 to 263-1 (NOTE: prior to C++20 the standard allows for different signed integer representations so in theory the limits listed may differ by +/- 1). If a calculation results in values outside of this range you will get integer over flow and your value will continue from the other end of the range. This is the reason you see negative values - the 239-th Fibonacci number is actually very big(it has 50 digits in its decimal notation) and can not be stored in any built-in data type.
On the other hand to compute only the last digit of the 239-th Fibonacci number you do not need to actually compute the whole value. In fact for any number in decimal notation its last digit is the remainder of the number when divided by 10 (i.e. the last digit of X is X%10). This also applies for arithmetic operations for instance the last digit of A + B is (A % 10 + B % 10) % 10. I hope this tip helps you solve the problem on your own.
For starters pay attention to that this header
#include<stdio.h>
is redundant. Neither declaration from the header is used in your program.
And in C++ you should at least specify
#include <cstdio>
if a declaration from the header is required.
To get such a big fibonacci number as the 239-th fibonacci number you need to use a special library that provides services for processing big numbers or you have to write such services yourself by using for example the standard class std::string.
However to get the last digit of a fibonacci number there is no need to calculate the whole fibonacci number. It is enough to track only last digits.
Here is my naive approach.:)
#include <iostream>
#include <functional>
unsigned int get_fibonacci_last_digit_my_naive( unsigned int n )
{
const unsigned int Base = 10;
unsigned int a[] = { 0, 1 };
while (n--)
{
a[1] += std::exchange( a[0], a[1] );
a[1] %= Base;
}
return a[0];
}
int main()
{
unsigned int n = 0;
std::cin >> n;
std::cout << "The last digit of the " << n << "-th fibonacci number is "
<< get_fibonacci_last_digit_my_naive( n ) << '\n';
return 0;
}
The program output is
The last digit of the 239-th fibonacci number is 1
Or if to change the function main the following way
int main()
{
unsigned int n = 0;
std::cin >> n;
for ( unsigned int i = n; i < n + 10; i++ )
{
std::cout << "The last digit of the " << i << "-th fibonacci number is "
<< get_fibonacci_last_digit_my_naive( i ) << '\n';
}
return 0;
}
and to enter the number 230 then the program output will be
The last digit of the 230-th fibonacci number is 5
The last digit of the 231-th fibonacci number is 4
The last digit of the 232-th fibonacci number is 9
The last digit of the 233-th fibonacci number is 3
The last digit of the 234-th fibonacci number is 2
The last digit of the 235-th fibonacci number is 5
The last digit of the 236-th fibonacci number is 7
The last digit of the 237-th fibonacci number is 2
The last digit of the 238-th fibonacci number is 9
The last digit of the 239-th fibonacci number is 1

Number of Factors (Codechef Level:-Medium)

Alice has learnt factorization recently. Bob doesn't think she has
learnt it properly and hence he has decided to quiz her. Bob gives
Alice a very large number and asks her to find out the number of
factors of that number. To make it a little easier for her, he
represents the number as a product of N numbers. Alice is frightened
of big numbers and hence is asking you for help. Your task is simple.
Given N numbers, you need to tell the number of distinct factors of
the product of these N numbers.
Input First line of input contains a single integer T, the number of test cases.
Each test starts with a line containing a single integer N. The next
line consists of N space separated integers (Ai).
Output For each test case, output on a separate line the total number of factors of the product of given numbers.
Constraints 1 ≤ T ≤ 100, 1 ≤ N ≤ 10, 2 ≤ Ai ≤ 1000000
My Answer
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
long long int p = 1, a, c = 0;
while (n--) {
cin >> a;
p *= a;
}
for (int i = 1; i <= p; i++) {
if (p % i == 0)
c++;
}
cout << c << endl;
}
return 0;
}
When compiling my program in Codechef, only small numbers are being executed.The larger numbers cannot be compiled. So in Codechef the result is showing "Time Limit Exceeded(TLE)".
Your approach to the problem does not take advantage of an important aspect of it, that is, the number is already expressed as a product of some integers. Therefore, if you can find the prime factorization of each of those N numbers separately (can be done efficiently in O(logn), using the sieve algorithm), then it is as simple as counting the number of unique factors among them.

Converting from Decimal to BCD

// C++ program to convert a decimal
// number to binary number
#include <iostream>
using namespace std;
// function to convert decimal to binary
void decToBinary(int n)
{
// array to store binary number
int binaryNum[1000];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
So this is a program to convert Decimal numbers to Binary. Now I'm trying to convert Decimal Numbers to BCD. I get the concept, if I have a number like 215 for example, I separate each number [2,1,5] and then convert each number into binary so it would be 0010,0001,0101. I am just confused about implementing it.
First of all, your algorithm simply displays the binary representation of some number n, instead of dividing it into single digits and returning some set of their binary representation.
To make out lives easier, we will be using standard containers and standard algorithms:
[...] if i have a number like 215 for example, i seperate each number [2,1,5] and then covert each number into binary so it would be 0010,0001,0101
Great, it means that we need some sort of a container to hold those three representations, don't we? My choice would be std::vector, since it is incredibly simple and efficient! You can read more about it here.
The mentioned vector will eventually store the binary representations, but here we encounter another problem - we actually need to somehow represent them!
Fortunately enough, the standard gives us a great tool - std::bitset, which is explained here. It is primarily used to make binary operations easier, but one of its great features is that it's also extremely good at simply being a binary representation.
The final function could look like this:
auto dec_to_bin(int n)
{
std::vector<std::bitset<4>> repr;
while(n > 0){
repr.push_back(std::bitset<4>(n % 10));
n /= 10;
}
std::reverse(repr.begin(), repr.end());
return repr;
}
What is happening here?
We firstly create a vector of fixed size bitsets (of the size 4, since every decimal digit can be represented as four binary digits), then as long as our n is greater than zero (you already know why - you are using the same logic in your code), we add (using push_back) a new bitset, that will be treated as binary representation of modulo of your number (i.e. the last digit).
Keep in mind though, that by doing this, we created the vector in the reversed order. The last two things we have to do is simply reverse and return it!
Finally, we can use our function in main as such:
int main()
{
for(auto b : dec_to_bin(215)){
std::cout << b << ' ';
}
}
This will print 0010 0001 0101, which was your desired output for the number 215
Can't you just replace the % 2 and / 2 with % 10 and / 10? The variables will be named wrong but that's the algorithmic change.
You simply have to divide your integer by digits and call your function for each digit:
void decToBCD(int n) {
// array to store digits
int digits[10];
// counter for digits
int i = 0;
while (n > 0) {
// storing remainder in digit array
digits[i] = n % 10;
n = n / 10;
i++;
}
// printing binary representation of digits
for (int j = i - 1; j >= 0; j--) {
decToBinary(digits[j]);
cout << " ";
}
}
I would update what you have to return a string from decToBinary rather than printing to cout, you can then write decToBCD which uses modulo 10 to work out the integer for each digit of the number (in the same way you used modulo 2 and divide by 2 to get each bit in decToBinary), and call decToBinary for each integer digit and concatenates the strings of binary digits to give the full result.

Find number of palindromes that are anagrams in C++

I am taking part in an online programming contest for fun on http://www.hackerrank.com. One of the problems that I am working on is to find number of anagrams of a string that are palindrome as well. I have solve the problem but when I try to upload it it fails on a number of test cases. As the actual test cases are hidden from me I do not know for sure why its failing but I assume it could be a scalability issue. Now I do not want someone to give me a ready made solution because that would not be fair but I am just curious on what people think about my approach.
Here is the problem description from the website:
Now that the king knows how to find out whether a given word has an anagram which is a palindrome or not, he is faced with another challenge. He realizes that there can be more than one anagram which are palindromes for a given word. Can you help him find out how many anagrams are possible for a given word which are palindromes?
The king has many words. For each given word, the king needs to find out the number of anagrams of the string which are palindromes. As the number of anagrams can be large, the king needs number of anagrams % (109+ 7).
Input format :
A single line which will contain the input string
Output format :
A single line containing the number of anagram strings which are palindrome % (109 + 7).
Constraints :
1<=length of string <= 105
Each character of the string is a lowercase alphabet.
Each testcase has atleast 1 anagram which is a palindrome.
Sample Input 01 :
aaabbbb
Sample Output 01 :
3
Explanation :
Three permutation of given string which are palindrome can be given as abbabba , bbaaabb and bababab.
Sample Input 02 :
cdcdcdcdeeeef
Sample Output 02 :
90
As specified in the problem description input strings can be as large as 10^5, hence all palindromes for a large string is not possible since I will run into number saturation issues. Also since I only need to give a modulo (10^9 + 7) based answer, I thought of taking log of numbers with base (10^9 + 7) and after all computations take antilog of fraction part with base (10^9 + 7) of the answer since that will be the modulo anyway.
My algorithm is as follows:
Store freq of each char (only need to look half of the string since
second half should be same as first one by def of palindrome)
If there are more than one char appearing with odd number of time no palindrome possible
Else for each char's freq incrementally calculate number of palindromes (Dynamic Programming)
For the DP following is the subproblem:
previous_count = 1
For each additional character added number of palindromes = previous_count * (number_of_char_already_seen + 1)/(number of char same as current char)
Here is my code:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <fstream>
using namespace std;
#define MAX_SIZE 100001
void factorial2 (unsigned int num, unsigned int *fact) {
fact[num]++;
return;
}
double mylog(double x) {
double normalizer = 1000000007.0;
return log10(x)/log10(normalizer);
}
int main() {
string in;
cin >> in;
if (in.size() == 1) {
cout << 1 << endl;
return 0;
}
map<char, int> freq;
for(int i=0; i<in.size(); ++i) {
if (freq.find(in.at(i)) == freq.end()) {
freq[in.at(i)] = 1;
} else {
freq[in.at(i)]++;
}
}
map<char, int> ::iterator itr = freq.begin();
unsigned long long int count = 1;
bool first = true;
unsigned long long int normalizer = 1000000007;
unsigned long long int size = 0;
unsigned int fact[MAX_SIZE] = {0};
vector<unsigned int> numerator;
while (itr != freq.end()) {
if (first == true) {
first = false;
} else {
for (size_t i=1; i<=itr->second/2; ++i) {
factorial2(i, fact);
numerator.push_back(size+i);
}
}
size += itr->second/2;
++itr;
}
//This loop is to cancel out common factors in numerator and denominator
for (int i=MAX_SIZE-1; i>1; --i) {
while (fact[i] != 0) {
bool not_div = true;
vector<unsigned int> newNumerator;
for (size_t j=0; j<numerator.size(); ++j) {
if (fact[i] && numerator[j]%i == 0) {
if (numerator[j]/i > 1)
newNumerator.push_back(numerator[j]/i);
fact[i]--; //Do as many cancellations as possible
not_div = false;
} else {
newNumerator.push_back(numerator[j]);
}
}
numerator = newNumerator;
if (not_div) {
break;
}
}
}
double countD = 0.0;
for (size_t i=0; i<numerator.size(); ++i) {
countD += mylog(double(numerator[i]));
}
for (size_t i=2; i <MAX_SIZE; ++i) {
if (fact[i]) {
countD -= mylog((pow(double(i), double(fact[i]))));
fact[i] = 0;
}
}
//Get the fraction part of countD
countD = countD - floor(countD);
countD = pow(double(normalizer), countD);
if (floor(countD + 0.5) > floor(countD)) {
countD = ceil(countD);
} else {
countD = floor(countD);
}
count = countD;
cout << count;
return 0;
}
Now I have spent a lot of time on this problem and I just wonder if there is something wrong in my approach or am I missing something here. Any ideas?
Note that anagrams are reflexive (they look the same read from the back as from the front), so half the occurrences of each character will be on one side and we just need to calculate the number of permutations of these. The other side will be an exact reversal of this side, so it doesn't add to the number of possibilities. The odd occurrence of a character (if one exists) must always be in the middle, so it can be ignored when calculating the number of permutations.
So:
Calculate the frequencies of the characters
Check that there's only 1 odd frequency
Divide the frequency of each character (rounding down - removes any odd occurrence).
Calculate the permutation of these characters using this formula:
(as per Wikipedia - multiset permutation)
Since the above terms can get quite big, we might want to split the formula up into prime factors so we can cancel out terms so we're left with only multiplication, then I believe we can % 109 + 7 after each multiplication, which should fit into a long long (since (109+7)*105 < 9223372036854775807).
Thanks to IVlad for pointing out a more efficient method of avoiding overflow than above:
Notice that p = 109 + 7 is a prime number, so we can use Fermat's little theorem to compute the multiplicative inverses of the mi mod p, and multiply by these and take the mod at each step instead of dividing. mi-1 = mi(10^9 + 5) (mod p). Using exponentiation by squaring, this will be very fast.
I also found this question (which also has some useful duplicates).
Examples:
Input: aaabbbb
Frequency:
a b
3 4
Div 2:
a b
1 2
Solution:
3!/2!1! = 3
Input: cdcdcdcdeeeef
Frequency:
c d e f
4 4 4 1
Div 2:
c d e f
2 2 2 0
Solution:
6!/2!2!2!0! = 90
The basic formula is:
p!/(a!*b!...*z!)
where p is floor of length/2 of the word and a,b,c..,z denotes the floor of half of frequency of occurrences a,b,c..,z in the word receptively.
The only problem now you are left is how to calculate this. For that, check this out.

How to get one individual digit from a number that has more than one digit in it

So I have a four digit number that is player-input in a simple puzzle I am making, I want to be able to check each digit, say I want to check the second digit to the right, if the number happens to be 4601 then of course it will be 6 but is their a faster way other than testing every single four digit number?
I found a few results with search but they didn't help, they just confused me more, please phrase any answers so anyone can understand them.
Also i am using c++.
To retrieve the second most significant (base ten) digit from an arbitrary integer i you could do:
while (i >= 100)
i /= 10;
return i % 10;
Of course, this assumes the number greater than or equal to 10 to begin with. If you need to preserve the number, then you will (obviously) want to be operating on a copy.
EDIT:
One could define a function for extracting an arbitrary digit using either arithmetic or string operations.
Arithmetic solution:
int extractDigit(size_t digit, int n) {
int mask = 1;
while ( digit --> 0 )
mask *= 10;
if (n < mask / 10) { // insufficient digits
return -1; // or some other appropriate error handling.
while ( n >= mask )
n /= mask;
return n % 10;
}
String solution:
#include <sstream>
#include <string>
using std::string;
using std::stringstream;
int extractDigit(size_t digit, int n) {
string result = static_cast<stringstream&>(stringstream() << n).str();
if (result.size() < digit) {
return -1;
}
return result[digit-1] - '0';
}
Both of these solutions implicitly assume that n will be non-negative. You could enforce this pre-condition by using an unsigned data type if you need to. Also, both of these functions are defining the digit positions such that the most significant is in position 1, and the positions increase to the right.
I am not guessing anything about what you going to do after you have the digit.But if its only the digit you want to have then you could use below:
int a=1234;
char b[4];
sprintf(b,"%d",a);
char c=b[1];
Now c has the second digit of your 4 digit number.
like wise you can access all the digits using the index to character array b
for a c++ equivalent pls see below:
std::ostringstream out;
out << age;
Now out.str()[1] will show the second digit.
You can read the number as an int and convert it to a char array and check each char as a digit
Example:
char digits[5];
int number;
//Read number in
scanf("%d",&number);
//Make sure it's 4 digits
number%=10000;
//Convert it to a char array
sprintf(digits,"%d",number)
if(digits[1]=='6')
{
//do stuff
}