Determining if a number is prime

后端 未结 20 1320
悲哀的现实
悲哀的现实 2020-11-30 03:05

I have perused a lot of code on this topic, but most of them produce the numbers that are prime all the way up to the input number. However, I need code which only checks w

20条回答
  •  迷失自我
    2020-11-30 03:26

    #define TRUE 1
    #define FALSE -1
    
    int main()
    {
    /* Local variables declaration */
    int num = 0;
    int result = 0;
    
    /* Getting number from user for which max prime quadruplet value is 
    to be found */
    printf("\nEnter the number :");
    scanf("%d", &num);
    
    result = Is_Prime( num );
    
    /* Printing the result to standard output */
    if (TRUE == result)
        printf("\n%d is a prime number\n", num);
    else
        printf("\n%d is not a prime number\n", num);
    
    return 0;
    }
    
    int Is_Prime( int num )
    {
    int i = 0;
    
    /* Checking whether number is negative. If num is negative, making
    it positive */
    if( 0 > num )
        num = -num;
    
    /* Checking whether number is less than 2 */
    if( 2 > num )
        return FALSE;
    
    /* Checking if number is 2 */
    if( 2 == num )
        return TRUE;
    
    /* Checking whether number is even. Even numbers
    are not prime numbers */
    if( 0 == ( num % 2 ))
        return FALSE;
    
    /* Checking whether the number is divisible by a smaller number
    1 += 2, is done to skip checking divisibility by even numbers.
    Iteration reduced to half */
    for( i = 3; i < num; i += 2 )
        if( 0 == ( num % i ))
            /* Number is divisible by some smaller number, 
            hence not a prime number */
            return FALSE;
    
    return TRUE;
    }
    

提交回复
热议问题