We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Dynamic Programming
  4. Lucky Numbers
  5. Discussions

Lucky Numbers

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • mateusmuller55
    7 years ago+ 2 comments

    I made this code in C. It works with the sample case, but I fail in all the test cases due to timeout. Why is that?

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    #include <assert.h>
    #include <inttypes.h>
    int checkPrime(uint64_t s){ /*gets a number and return 1 for prime or 0 otherwise*/
        uint64_t i;
        if (s <= 1)
            return 0;
        if (s == 2)
            return 1;
        if (s % 2 == 0 && s > 2)
            return 0;
        else for (i = 3; i < s/2; i += 2){
            if (s % i == 0)
                return 0;
        }
        return 1;
    }
    int sumSqrDigits(uint64_t a){ /* sum the square of all digits of a number*/
        uint64_t s = 0;
        if (a <= 10)
            return 0;
        while (a  > 0){
            s += (a%10)*(a%10);
            a = a/10;
        }
        return checkPrime(s); /* checks if the sum is a prime number*/
    
    }
    int sumDigits(uint64_t a){ //sum the digits of a number
        uint64_t s = 0;
        if (a <= 10)
            return 0;
        else while (a  > 0){
            s += a%10;
            a = a/10;
        }
        return checkPrime(s); /* checks if the sum is a prime number*/
    }
    int luckyNumbers(uint64_t a, uint64_t b) { /*iterates through all numbers between a and b (included)*/
    
        uint64_t ans = 0, i;
        for (i = a; i <= b; i++){
    
            if ((sumDigits(i) == 1) && (sumSqrDigits(i) == 1)){ // checks if both results are prime
    
            ans++;
            //printf("%"PRIu64"\n", ans);
    
            }
        }
        return ans;
    }
    
    int main() {
        uint64_t a, b, i, cases;
        scanf("%"SCNu64, &cases);
        uint64_t ans[cases];
    
        for(i = 0; i < cases; i++) {
            scanf("%"SCNu64 "%"SCNu64 , &a, &b);
    
            ans[i] = luckyNumbers(a, b);
    
        }
        for (i = 0; i < cases; i++){
            printf("%"PRIu64"\n", ans[i]);
        }
    
        return 0;
    }
    
    4|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy