0

How to find smallest n digit prime number as well as largest?

12th Sep 2021, 10:06 AM
sparkle
5 Réponses
+ 2
Please show your attempt.
12th Sep 2021, 10:18 AM
Rupali Haldiya
Rupali Haldiya - avatar
+ 3
#include <stdio.h> int main() { int i, Num, prime,largestprime; for(Num = 100; Num <1000 ; Num++) { prime = 0; for (i = 2; i <= Num/2; i++) { if(Num%i == 0) { prime++; break; } } if(prime == 0) { if(Num>100){ printf("the smallest three digit prime number is:%d ",Num); break; } } } return 0; } Here i found smallest using break... For largest what can i do
12th Sep 2021, 10:47 AM
sparkle
+ 1
#include <stdio.h> #define smallest_tested 100 #define largest_tested 1000 int test_for_prime(int some_number){ // Going to loop through all numbers, can be slow if we are testing large numbers for (int i = 2; i <= some_number/2; i++){ //placed int i in the loop no reason to create a global variable. if(some_number % i == 0){ return 1; } } return 0; } int main(void){ // removed two variable I dont think are needed as globals. int smallest_prime,largest_prime; smallest_prime = largest_tested; //initilizing them at opposites to allow greater than less than test to work. largest_prime = smallest_tested; // looks like you are only testing 100 to 1000 so I will stick with that for(int number_to_test = smallest_tested; number_to_test < largest_tested ; number_to_test++){ if(test_for_prime(number_to_test) == 0){ if(number_to_test < smallest_prime){ smallest_prime = number_to_test; } if (number_to_test > largest_prime){ largest_prime = number_to_test; } } } printf("The smallest prime number between 100 and 1000 is %i, the largest prime number between 100 and 1000 is %i\n", smallest_prime, largest_prime); return 0; } Now its your turn change it so you get a min and maximum number to test not just 100 to 1000.
12th Sep 2021, 1:08 PM
William Owens
William Owens - avatar