C++: Counting zeros at the end optimization - c++

I am trying to solve standard problem of calculating 0s at the end of factorial of any natural number. My code works fine but online judge gives "Time Limit Exceeded" error. Decided to ask here about how I can optimize my code.
#include <iostream>
using namespace std;
int count (int n)
{
int result = 0;
for (unsigned int i = 5; i <= n; i += 5)
{
int temp = i;
while (!(temp % 5))
{
++result;
temp /= 5;
}
}
return result;
}
int main()
{
int N;
cin >> N;
cin.get();
for (unsigned int i = 0; i < N; ++i)
{
int n;
cin >> n;
cin.get();
cout << count (n) << endl;
}
return 0;
}
Thanks in advance.

Try this:
int count (int n)
{
int result = 0;
for (unsigned int i = 5; i <= n; i *= 5)
result += n / i;
return result;
}
In 1*2*..*N, there are N/5 factors, which are divisable by 5. N/25 of those are also divisable by 25, ...

You haven't to check every number divisible by 5. Instead you can count 5's with simple series:
count = n div 5 + n div 25 + n div 125...

Related

A number K and an Array of size N is given, check whether we can get the sum of any two elements of array equal to K

I tried to solve the problem but my code still contains some bugs. Why isn't it running?
Here is the link of the question website: https://www.hackerearth.com/practice/data-structures/hash-tables/basics-of-hash-tables/practice-problems/algorithm/pair-sums/?
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
const int n = 1e7 + 10;
int hsh[n];
int main()
{
int n, k;
cin >> n >> k;
int A[n];
for (int i = 0; i < n; i++)
{
cin >> A[i];
}
for (int i = 0; i < n; i++)
{
hsh[A[i]] = k - A[i];
}
int t = 0;
for (int i = 0; i < n; i++)
{
if (hsh[A[i]] == k - hsh[hsh[A[i]]])
{
cout << "YES";
t = 1;
break;
}
}
if (t == 0)
{
cout << "NO";
}
return 0;
}
The problem is that while hsh[A[i]] is always valid, hsh[hsh[A[i]] is not.
Consider the following input:
1 1
10000
This does the following:
A[0] = 10000;
...
hsh[10000] = 1 - 10000; // = -99999
...
if (hsh[10000] == 1 - hsh[-99999]) {...}
So your code is reading out of bounds of the array hsh[]. Make sure you check first if hsh[A[i]] >= 0.
Note that your code is more complicated than necessary; you can do a single loop over the input to check if there is a matching pair:
#include <iostream>
static constexpr int max_k = 2e6;
static bool seen[max_k + 1];
int main()
{
int n, k;
std::cin >> n >> k;
for (int i = 0; i < n; ++i)
{
int A;
std::cin >> A;
if (A <= k && seen[k - A]) {
std::cout << "YES\n";
return 0;
}
seen[A] = true;
}
std::cout << "NO\n";
}

What's wrong with factorial function code in this Pascal triangle?

can anyone explain why first fact() function code doesn't give me correct output but second one does?
what's wrong with the commented factorial function code???
#include <iostream>
using namespace std;
// int fact(int n){
// for (int i = n-1; i > 0; i--){
// n = n * i;
// }
// return n;
// }
int fact(int n){
int temp=1;
for (int i = 2; i <=n; i++){
temp= temp * i;
}
return temp;
}
int nCr(int n, int r){
int temp=(fact(n) / (fact(n - r) * fact(r)));
return temp;
}
int main(){
int n;
cout << "enter no: ";
cin >> n;
for (int i = 0; i < n;i++){
for (int k = 1; k < (n - i);k++)
cout << " ";
for (int j = 0; j <= i; j++)
{
cout << nCr(i, j) << " ";
}
cout << endl;
}
return 0;
}
The second fact function correctly returns 1 when n = 0, but the first one wrongly returns 0 when n = 0.
Adding check for this case will make the first function work well.
int fact(int n){
if (n == 0) return 1; // check for n = 0 case
for (int i = n-1; i > 0; i--){
n = n * i;
}
return n;
}

Function does not return a value, while using a vector in c++

The below function works fine when using an integer array(minNumCoins) but does not return anything while using a vector instead of an array. Can anyone tell me why?
int dp_change(const vector<int> &coins, int money, int n){
//vector<int> minNumCoins(n);
int minNumCoins[n];
int numCoins = 0;
minNumCoins[0] = 0;
for( int m = 1; m <= money; m++){
minNumCoins[m] = 100000;
for(int i = 0; i < coins.size(); i++){
if(m >= coins[i]){
numCoins = minNumCoins[m - coins[i]] + 1;
if(numCoins < minNumCoins[m]){
minNumCoins[m] = numCoins;
}
}
}
}
//return minNumCoins.at(money);
return minNumCoins[money];
}
Main function
int main() {
int n, money;
cin >> money;
cin >> n;
vector<int> coins(n);
for(int i = 0; i < n; i++){
cin >> coins[i];
}
//int num_of_coins = dp_change(coins, money);
cout << "Number of coins = " << dp_change(coins, money, n);
return 0;
}
Sample
Input:
> 20 <br>
2 <br>
10 <br>
1
Output:
Number of coins = 2
In this piece of code:
for( int m =1 ; m<=money; m++){
minNumCoins[m] = 100000;
m can become out of bounds if money >= n, which it is in your example input (money=20, n=2). As a result, your program crashes before it gets to output anything.
int dp_change(const vector<int> &coins, int money, int n){
vector<int> minNumCoins(n);
//int minNumCoins[n];
int numCoins = 0;
minNumCoins[0] = 0;
for( int m =1 ; m<n; m++){
minNumCoins[m] = 100000;
for(int i=0; i< coins.size(); i++){
if( m >= coins[i]){
numCoins = minNumCoins[m-coins[i]] +1;
if( numCoins < minNumCoins[m]){
minNumCoins[m] = numCoins;
}
}
}
}
//return minNumCoins.at(money);
return minNumCoins[any value which is less then n (0-(n-1))];
}
Let me know whether my suggestion works or not.
Some things might cause the error while using vector.
you were checking in the outer loop..
for( int m =1 ; m<=money; m++){
here I think m<n will be the correct condition for the loop to work.
If money is bigger than n, then out-of-bounds error will occur thus resulting in the code crash. if money = 10, n = 4, then the array out of bound error will occur.
plus return will be like this.
return minNumCoins[n];
Or you can declare the minNumCoins array with size minNumCoins[money]
Now implement your logic properly and hopefully, you'll get the desired result.

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}

Hollerith's Radix Sort

I have implemented the normal Radix Sort:
#include <iostream>
using namespace std;
void print(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int findMax(int arr[], int n) {
int mx = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
const int m = findMax(arr, n) + 1;
int C[m];
for (int i = 0; i < m; i++) {
C[i] = 0;
}
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[C[(arr[i] / exp) % 10] - 1] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
void radixSotr(int arr[], int n) {
int m = findMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << endl;
cout << "Unsorted version of the array: " << endl;
print(arr, n);
cout << endl;
cout << "Sorted version of the array: " << endl;
radixSotr(arr, n);
print(arr, n);
return 0;
}
Now I am trying to implement Hollerith's version of Radix Sort, where the Radix Sort starts with the most significant bit and propagates iteratively to the least significant bit. Could you give me any ideas how to modify my code, because I am stuck.
Your countingSort function has a problem:
you should use an array of 10 indexes for counting instead of finding the largest element and declaring int C[m]. Your current code allocates a potentially huge array in automatic storage, invoking undefined behavior.
Here is a corrected version:
void countingSort(int arr[], int n, int exp) {
int output[n];
int C[10] = { 0 };
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[--C[(arr[i] / exp) % 10]] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
Note that this algorithm cannot sort an array with negative numbers.
The Hollerith algorithm uses least significant digit to most significant digit. It was invented for sorting US Census data tabulated on punched cards using tabulating machines. This is a very early example of computing for data processing that goes back to 1887. Punch cards used 2 different character encoding schemes named H-code and T-code all the way to the end of the 20th century, H standing for Herman Hollerith, inventor of these sorting machines, who died in 1929. (see http://ed-thelen.org/comp-hist/Knuth-Sort.html )
For the most significant bit down to the least significant bit, you need recursion, not an iterative method like the one you have:
Find the maximum value, hence the maximum exponent to get the most significant digit.
Sort the array according to the current digit
For each bucket of elements with the same digit at the current position:
if the bucket is empty or has only one element, it is sorted
otherwise, recurse on the bucket for the next lesser digit, using exp/10.
You can do this with any base >= 2.