In this HackerRank Sherlock and Squares problem, you need to complete the squares function that should return an integer representing the number of square integers in the inclusive range from a to b.
Problem solution in Python programming.
t = int(input()) for i in range (0,t): count = 0 a,b = [int(j) for j in input().strip().split()] square1 = a ** (.5) if (square1 != int(square1)): a1 = int(square1) + 1 else: a1 = int(square1) square2 = b ** (.5) b1 = int(square2) count = b1 - a1 +1 print(count)
Problem solution in Java Programming.
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner in = new Scanner(System.in); int square_count = 0; int test_cases = in.nextInt(); int from; int to; int squareroot; for (int i = 0; i < test_cases; i++) { from = in.nextInt(); to = in.nextInt(); int a = (int)Math.ceil(Math.sqrt(from)); int b = (int)Math.floor(Math.sqrt(to)); square_count = b - a + 1; System.out.println(square_count); } in.close(); } }
Problem solution in C++ programming.
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n,m; cin>>n; while (cin>>n>>m) { cout<<(int)(sqrt(m)+0.0000001)-(int)(sqrt(n-1)+0.0000001)<<endl; } return 0; }
Problem solution in C programming.
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { //Grab the number of tests. int T; scanf( "%d", &T ); //Check for SQ T times. for( int i = 0; i < T; i++ ) { long long int A; scanf( "%llu", &A ); long long int B; scanf( "%llu", &B ); long long int count = 0; long long int sqA = sqrt( A ); long long int sqB = sqrt( B ); long double sqDoub = (long double)A; sqDoub = sqrt( A ); if( sqDoub != sqA ) count--; count += sqB - sqA + 1; printf( "%llun", count ); } return 0; }
Problem solution in JavaScript programming.
function processData(input) { //Enter your code here var lines = input.split('n'); var testCount = lines[0]; for(var i=1;i<lines.length;++i){ var test = lines[i].split(' '); var hit = 0; var min = Math.ceil(Math.sqrt(test[0])); var max = Math.sqrt(test[1]); for(var j = min; j <= max; ++j){ if( (j * j)<= test[1] ) hit += 1; } console.log(hit); } } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); });