Count of numbers up to N having at least one prime factor common with N | Java program for the above approach ; Function to count all the numbers in the range [ 1 , N ] having common factor with N other than 1 ; Stores the count of numbers having more than 1 factor with N ; Iterate over the range [ 1 , N ] ; If gcd is not 1 then increment the count ; Print the resultant count ; Driver Code
import java . util . * ; class GFG { static void countNumbers ( int N ) { int count = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { if ( __gcd ( i , N ) != 1 ) count ++ ; } System . out . print ( count ) ; } static int __gcd ( int a , int b ) { return b == 0 ? a : __gcd ( b , a % b ) ; } public static void main ( String [ ] args ) { int N = 5 ; countNumbers ( N ) ; } }