Java program to get number of elements with odd factors in given range



In this article, we will learn how to count the number of elements with odd factors (i.e., perfect squares) in a given range using Java. Perfect squares have odd divisors, and we can calculate them by counting the perfect squares in the specified range.

Problem Statement

Given a range defined by a lower and upper bound, write a Java program to calculate how many numbers in this range have odd factors (i.e., perfect squares).
Input
Lower Range: 55
Upper Range: 1000
Output
The number of elements with odd factors between 55 and 1000 is: 24

Steps to calculate the number of elements with odd factors in a given range

The following are the steps to calculate the number of elements with odd factors in a given range?

  • Import necessary classes (java.util., java.lang., java.io.).
  • Create a function that calculates the number of perfect squares between the given range.
  • Use the square root function to find the range of perfect squares.
  • Implement the logic to compute the count of elements with odd factors.
  • Print the result showing the count of numbers with odd factors.

Java program to count the number of elements with odd factors in a given range

The following is an example of calculating the number of elements with odd factors in a given range ?

import java.io.*;
import java.io.*;
import java.util.*;
import java.lang.*;

public class Main {
	public static int square_count(int low_range, int high_range) {
		return (int)Math.pow((double)high_range, 0.5) - (int)Math.pow((double)low_range - 1, 0.5);
	}

	public static void main(String[] args) {
		int low_range = 55, high_range = 1000;
		System.out.print("The number of values with odd factors between a given range of numbers "
		                 + "is : " + square_count(low_range, high_range));
	}
}

Output

The number of values with odd factors between a given range of numbers is : 24

Code Explanation

A class named Demo contains a function named ?square_count'. This function is defined by passing two integer values as parameters. It returns the number of elements that have odd factors given a specific range. This is done by using the math function ?pow'. In the main function, the lower range and higher range values are defined and the function ?square_count' is called with the lower and higher range values. The relevant message is displayed on the console.

Updated on: 2024-11-18T22:29:39+05:30

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements