DMOJ · ccc09s1

CCC 2009 S1 Cool Numbers

This C++ solution uses binary search for CCC 2009 S1 Cool Numbers. Read the reasoning, inspect the code, or try your own test case below.

ccc09s1CCC 2009 S1Sorting & searchingBinary searchC++39 lines
Solution056of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Binary search

Cool Numbers asks for numbers in [A,B] that are both perfect squares and cubes, equivalently sixth powers; the code counts exactly those.

Sorting & searching

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

cool_numbers.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    int main(){
        vector<int> vec;
        for(int i = 0;; i++){
            int range = pow(i, 6);
            if(range > 1e8) break;
             vec.push_back(range);
        }
        int a, b;
        cin >> a >> b;
        int cnt, l, r;
        l = lower_bound(vec.begin(), vec.end(), a) - vec.begin();
        r = upper_bound(vec.begin(), vec.end(), b) - vec.begin();
        cnt = r - l;
        cout << cnt << endl;
    }
    //faster solution using scanf
    /*
    #include <stdio.h>
    #include <math.h>
     
    int main()
    {
    	int a,b;
    	scanf("%d",&a);
    	scanf("%d",&b);
     
    	int i = 0;
    	int count = 0;
    	while (pow(i,6) <= b) {
    		if (pow(i,6) >= a) count++;
    		i++;
    	}
     
    	printf("%d\n",count);
     
    	return 0;
    }*/
     
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.