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.
Related
Once, when Dino was solving a problem related to arrays, he saw that the size of all arrays is at most 106. Since Dino is a dinosaur, this number seemed very small to him. Therefore, he decided to create a big array.
Dino first creates an empty array and selects n pairs of numbers: (a1, b1), (a2, b2), ..., (an, bn). Then for each of these pairs he inserts into array the number bi ai times. For example,if the first pair is (3, 5), the number 5 will be inserted into array 3 times. After that, Dino decides to arrange this array in non-decreasing order, but since the array is very large, Dino's computer cannot perform this arrangement. He is interested in the k-th (the array is numbered starting from 1) number. Help Dino to find this number.
Input
First line contains number n (1 ≤ n ≤ 105). Each of the next n lines contains pair (ai, bi) (1 ≤ ai, bi ≤ 105). The last line contains number k. It is guaranteed that k-th number exists in array.
Output
Print the k-th number in non-decreasing array.
INPUT
First line contains number n (1 ≤ n ≤ 105). Each of the next n lines contains pair (ai, bi) (1 ≤ ai, bi ≤ 105). The last line contains number k. It is guaranteed that k-th number exists in array.
OUTPUT
Print the k-th number in non-decreasing array.
INPUT Examples
3
1 2
3 6
2 1
3
OUTPUT
2
I tried to code this my self but it got partially accepted. Can someone help me for doing this?
#include<iostream>
#include<algorithm>
#include<utility>
#include<vector>
using namespace std;
using ull = unsigned long long;
int main()
{
ull a, b, n, j, k;
cin >> n;
vector<ull> myvec;
for(int i = 0; i < n; i++)
{
cin >> a >> b;
for(j = 0; j < a; j++)
{
myvec.push_back(b);
}
}
cin >> k;
sort(myvec.begin(), myvec.end());
cout << myvec[k - 1];
return 0;
}
You don't need to recreate the array, and you don't need to sort anything (the description even tells you that you shouldn't: "Dino's computer cannot perform this arrangement").
Consider what happens if you turn the problem around slightly.
Instead of a[i] being the i:th number, let it say how many is there are in total.
(The arrangement of the input hints at this, although not as obviously as the "sorting won't work" hint.)
This essentially makes a run-length encoded sorted array, with the indices of a doubling as elements, and the elements of a are the run lengths.
Then consider that a linear search through 105 elements (bi ≤ 105) is way faster than sorting 106 elements.
Something like this:
int main()
{
// Keeps track of the total number of occurrences of each number.
// The values are all less than or equal to 100000.
// Add an extra element to simplify the rest of the code.
// (The zero will be unused.)
std::vector<int> counts(100001);
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
int count, value;
cin >> count >> value;
counts[value] += count;
}
int k;
cin >> k;
// Now go looking for the k:th number, adjusting k as we go.
for (size_t number = 0; number < counts.size(); number++)
{
if (k <= counts[number])
{
std::cout << number << std::endl;
break;
}
// Adjust k for the rest of the sequence.
k -= counts[number];
}
}
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
First of all, I would clarify that I am new to programming and started with c++ recently. There was a problem related to Legendre's formula in my math textbook and I thought about making a program related to it. It takes a number from user n, and finds the highest power of n which divides n!
It runs fine for a lot of numbers but messes up for a few others and it is completely random. This is a snippet from the code.
#include <iostream>
#include <math.h>
using namespace std;
int prime(int);
int calc(int, int);
int main()
{
int n;
int hpf=2;
cout<<"This program finds highest power x that divides x!"<<endl;
cout << "Enter number : " << endl;
cin>>n;
for(int i=2; i<=n; i++)
{
bool p=prime(i);
if(p==true && n%i==0)
hpf=i;
}
cout<<"The highest prime factor of the number is : "<<hpf<<endl;
int p=calc(hpf, n);
cout<<"The highest power of "<<n<<" that divides "<<n<<"!"<<" is : "<<p;
return 0;
}
calc(int f, int n)
{
int c=0 , d=1, power=1, i=0;
while(i>=0)
{
int x= pow(f,power+i);
if(i>0 && n%x==0)
d++;
if(x<=n)
{
c+=n/x;
i++;
}
else
break;
}
return c/d;
}
prime(int n)
{
bool isPrime = true;
for(int i = 2; i <= n/2; i++)
{
if (n%i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
I pass the highest prime factor of n and the number n itself to int calc(int, int).
Now here is the problem:
when I input n=9, I get
Enter number :
9
The highest prime factor of the number is : 3
The highest power of 9 that divides 9! is : 2
on the other hand, if I input 25, I get
Enter number :
25
The highest prime factor of the number is : 5
The highest power of 25 that divides 25! is : 6
This is clearly wrong, the highest power should be 3.
It also works for bigger numbers accurately, but not all.
PS: I use codeblocks.
I'm not sure why exactly it works for 9 and not for 25(your program seems fine, but you probably have a problem when you calculate d or something), although both are squares of primes and your code seems to take care of that, but I do know why it doesn't work with number like 12. This happens because your code only looks at the highest prime factor and ignores the others. This will give you the true result when the other prime factors appear less frequently then the biggest one, but in all other cases this assumption leads to wrong results, because the highest is then also limited by smaller primes. So a correct solution has to take care of all prime factors.
For that you first need to factor the number(getting the prime factors and their power!). You can just google that if you are unsure how to do that. I don't want to include it here because then the answer would get to long.
Then you need to find how often the number is present in the factorial.
As you already know(at least you used it in your code) you can count by summing up the occurence as a factor of each power of the prime in every factor of the factorial which can be done through division like this:
n/p¹ + n/p² + n/p³ + n/p⁴ + …
That can be put into a simple function(using a simple self-made power calculation):
int occurenceInFaculty(int factor, int faculty) {
int sum = 0;
for(int power = factor; power <= faculty; power *= factor) { // Go through all powers
sum += faculty/power;
}
return sum;
}
Now you can calculate the occurrence for each of the prime factors of your number and if you divide by the power of that prime factor in the factorization you get an upper limit for the highest power.
Then all that's left to do is take the minimum over all prime factors and you are done.
Assuming one possible way of storing the prime factorization here is what the resulting code could look like:
Somewhere in the beginning of your code:
typedef struct {
int prime;
int power;
} PrimeFactor;
Assuming a prime factorization method like this:
PrimeFactor* factorization(int number, int* factors) {
// Factorize here. Return a pointer to an array of PrimeFactors and set the pointer factors to the arrays length.
}
And then the calculation part:
int number = 25; // Put your number here.
int length = 0;
PrimeFactor* factors = factorization(25, &length);
int min = number; // Some reasonable upper border because n! < n^n
for(int i = 0; i < length; i++) {
if(occurenceInFaculty(factors[i].prime, number)/factors[i].power < min)
min = occurenceInFaculty(factors[i].prime, number)/factors[i].power;
}
This program also gets 25 right!
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.
i am trying this but on input>10000 this loop id taking much more time.
is there is any way to optimize this which has time complexity less then N or (logn)?
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
int n = 10001;
for (int i = 1; i < n; i++) {
if (n % i == 0) {
cout << i;
}
}
return 0;
}
In addition to dmh2000's answer: You can exploit redundancies in the checking. For example, if a number is not divisible by n it is also not divisible by any multiple of n. For example a number that is not divisible by 2 also cannot be divided by 4, 6, or 8.
This technique is known as sieving.
you can iterate up to just the square root of n rather than n, since anything bigger than the square root can't be a factor of n. edit : read ComicSansMs answer was better than my edit
First step is to find all the prime factors, with their multiplicity. Then you can generate the factors easily.
Finding the prime factors is quite fast on average for numbers up to about 100000000, if you do it sensibly. If you find a factor, you can divide it out of n, which reduces the time enormously in the general case. Also you only need to check odd factors up to sqrt(n), apart from 2:
// I assume n is non-zero
while (!(n & 1)) {
cout << "2" << endl;
n /= 2;
}
for (unsigned int factor = 3; factor * factor <= n; factor += 2) {
while (n % factor == 0) {
cout << factor << endl;
n /= factor;
}
if (n != 1)
cout << n << endl;
}
In case you need to perform this many times, there is a good solution. I'll give just an example, implementation will be your business.
Lets say you need to factorize two numbers, e.g. 580 and 72.
At first you factorize it into primes
580 = 2 x 2 x 5 x 29
72 = 2 x 2 x 2 x 3 x 3
Speed of factorization into primes could be highly increased using caching. You should have std::set<int> which contains all know prime numbers, so after factorizing 580 it contains 2, 5, 29. That means to factorize 72 you will only need to determine that 3 is prime.
After you have all prime factors you need to multiply them in all combinations to get non-prime factors.
As I mentioned this solution is really good only in case you need to factorize many numbers, but if you need to factorize only once it is just not bad Sieving would be better.