Tuesday, 26 August 2014

Problem analysis for Funny Numbers

PROBLEM: Funny numbers

This problem can be solved as follows:
Using Sieve of Eratosthenes, generate a array primes[] such that
primes[x] = 1 if x is prime.
Now for each input N, check for divisibility starting from 2 till square root of N.
whenever a number divides N, repeatedly divide it until, it is
not divisible by that number anymore. Each time it is divisible,
increment a count variable to keep track of the number
of prime factors.
If N != 1 after all the repeated divisions till sqrt(N), then, what remains is guaranteed to be prime number and hence increment count once again.
Next, check if primes[count] == 1.
If so, print Yes, else print No.

Problem setter's solution in C++:

#include <iostream>
#include <cmath>

using namespace std;

static const long long MAX = 1000000;

long long primes[MAX+1];


// uses sieve of Eratosthenes to generate prime numbers till 1000000
void init() {
    primes[1] = 1;
    primes[0] = 1;
    for(long long i = 2; i <= MAX; i++) {
        for(long long j = i*i; j <= MAX && !primes[i]; j += i) {
            //cout << j << endl;
            primes[j] = 1;

        }
    }
}

int main(void) {
    init();
    long long t;
    cin >> t;
    while(t--) {
        long long x;
        cin >> x;
        long long c = 0;
        int sq = sqrt(x);
        for(int i = 2; i <= sq; i++) {
            if(x%i == 0)
                c++;
            while(x%i == 0)
                x /= i;
        }
        if(x > 1)
            c++;
        if(!primes[c])
            cout << "Funny" << endl;
        else
            cout << "Not Funny" << endl;
    }
    return 0;
}

No comments:

Post a Comment