Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java รับจำนวนองค์ประกอบที่มีปัจจัยคี่ในช่วงที่กำหนด


เพื่อให้ได้จำนวนองค์ประกอบที่มีปัจจัยคี่ในช่วงที่กำหนด รหัส Java เป็นดังนี้ -

ตัวอย่าง

import java.io.*;
import java.util.*;
import java.lang.*;
public class Demo{
   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));
   }
}

ผลลัพธ์

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

คลาสชื่อ Demo มีฟังก์ชันชื่อ 'square_count' ฟังก์ชันนี้กำหนดโดยส่งค่าจำนวนเต็มสองค่าเป็นพารามิเตอร์ ส่งคืนจำนวนองค์ประกอบที่มีปัจจัยคี่ตามช่วงที่ระบุ ทำได้โดยใช้ฟังก์ชันทางคณิตศาสตร์ 'pow' ในฟังก์ชันหลัก ค่าช่วงที่ต่ำกว่าและช่วงที่สูงกว่าจะถูกกำหนด และฟังก์ชัน 'square_count' จะถูกเรียกด้วยค่าช่วงที่ต่ำกว่าและสูงกว่า ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล