First Prime
Difficulty: ⚫◯◯◯ (Easy)
Tags: linked-list, prime-numbers
Hurdle: Passing this question is sufficient to pass the linked list hurdle.
Description
Write a function first_prime that takes one argument head, where head is a pointer to the first node of a linked list.
The function should return the first prime number in the list. If there are no prime numbers in the list, the function should return -1.
A prime number is a whole number greater than 1 that is only exactly divisible (leaving no remainder) by 1 and itself.
Examples
Example 1
Input: 4 -> 11 -> 7 -> 9 -> X
Output: 11
Explanation: 11 is the first prime number in the list.
Example 2
Input: 4 -> 4 -> 4 -> X
Output: -1
Explanation: There are no prime numbers in the list.
Example 3
Input: 2 -> 3 -> 5 -> X
Output: 2
Explanation: 2 is the first (and smallest) prime number.
Function Signature
int first_prime(struct node *head);
Data Structure
struct node {
struct node *next;
int data;
};
Constraints
- The value
1is not considered to be a prime number. - Return
-1if the list is empty. - Do not modify the linked list.
- Do not use arrays.
- Do not call
malloc. - Do not call
scanf,getchar, orfgets. - Do not call
printf(the function should only return a value).
Test Cases
./first-prime 10 4 15 17
17
./first-prime 5 64 15 99 25
5
./first-prime 1 9
-1
./first-prime 16
-1
./first-prime 2 3 5
2