Need help making prime numbers row in {c} - c

I need to make a program in {c} that would give me prime number for entered number (example is user enter 50. to write back 229)
So, I am stuck when making loop.
I am tring to define for row[100] to have row[0]=2,row[1]=3 and then I make i=4 and try to make a loop that would for number i devide number i with every single number in the row (becose those I know are prime numbers) and get module (number after 0,not sure how it is said on english), and then if if all of them have module !=0 then I know it is prime number and I want to add it into row.
So is there a way somebody can help me write this line? Thanks alot in advance :)
#include <stdio.h>
int main ()
{
int i,numb=4,position,temp,temp1,row[100];
printf(" enter position (1-100)\n");
scanf("%d",&position);
if (position>100||position<0 )
{
printf("error,enter position between 1 and 100");
return(0);
}
row[0]=2;
row[1]=3;
i=2;
do
{
temp=numb%2;
temp1=numb%3;
if (temp!=0 && temp1!=0)
{
row[i]=numb;
i++;
}
numb++;
}
while (i<100);
printf("%d. prime number is %d",position,row[position]);
return 0;
}
Ok,so I need to change part where I ask for module from deviding wit 2 and 3 to asking for module from deviding from all numbers in row at that moment. Thank you for help

#include <stdio.h>
#define MAX_N 100
int main(void){
int i, odd, temp, position, n = 0, row[MAX_N];
row[n++]=2;
row[n++]=3;
for(odd = 5; n < MAX_N; odd += 2){
int is_prime = 1;//true
for(i = 1; i < n; ++i){
temp = row[i];
if(temp * temp > odd)
break;
if(odd % temp == 0){
is_prime = 0;//false
break;
}
}
if(is_prime)
row[n++] = odd;
}
printf(" enter position (1-%d)\n", MAX_N);
scanf("%d", &position);
if (position > 100 || position < 1){
printf("error,enter position between 1 and %d\n", MAX_N);
return 0;
}
printf("%d. prime number is %d", position, row[position - 1]);
return 0;
}

Related

Sorting array elements to find the largest and smallest number in C

I'm solving this problem where I need to give some inputs, find the largest and smallest among them. Here is the problem statement
Ivan Vasilyevich came to the market and decided to buy two watermelons: one for himself and another for the wife's mother. It is clear to choose for himself the heaviest watermelon, and for mother-in-law the lightest. But there is one problem: there are many watermelons and he does not know how to choose the lightest and the heaviest one. Help him!
Input
The first line contains the number of watermelons n (n ≤ 30000). The second line contains n numbers, each number is a mass of corresponding watermelon. All weights of watermelons are positive integers and do not exceed 30000.
Output
Print two numbers: the weight of watermelon that Ivan Vasilyevich will buy for his mother-in-law and the weight of watermelon that he will buy himself, or print the message "Ooops!" (without quotes), if someone left without watermelon
Here's my code
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
for (i = 0; i < n; i++)
{
if (w[0] < w[i])
w[0] = w[i];
gw = w[0];
}
for (i = 0; i < n; i++)
{
if (w[0] > w[i])
w[0] = w[i];
lw = w[0];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}
I'm getting wrong answer(96/100). What am I getting wrong?
You do not need to allocate space for an array of 30k integers to find the min and max weights entered.
First, initialize min and max weights to the first integer entered and then update min and max accordingly as you read more weights. Use the variable cur (an integer) to store the last integer (i.e. weight) read.
That way, you do it all in one pass, rather than in multiple loops.
If you use scanf, it is good practice to check it's return value. For reference (from the C99 standard):
The scanf function returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, the scanf function returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.
In our case, when our scanf call is of the form scanf("%d", &a) where a is some int, we expect the call scanf("%d", &a) to return 1.
While it is good practice to check the return value, it is not absolutely necessary. If this is a program for one of your classes and you have never worked with the return value of scanf, you could remove all the checks for the return value below and the program should function the same. That said, it would show great initiative if you do check for the return value and reference the C standard in your justification for checking it (as the return value provides very useful information).
#include <stdio.h>
#include <stdlib.h>
#define MAX_WAT 30000 /* maximum number of watermelons */
int main(void) {
int n, i, min, max, cur;
/* prompt user for number of watermelons */
printf("Enter number of watermelons: ");
/* read integer, checking return value of scanf as expected */
if (scanf("%d", &n) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (n > MAX_WAT) {
printf("Please enter less than %d watermelons.\n", MAX_WAT);
return 0;
}
/* if zero or one watermelons, at least one person leaves without */
if (n <= 1) {
printf("Ooops!\n");
return 0;
}
/* initialize min, max to first integer and update
min, max accordingly as new weights are read */
printf("Enter weights of %d watermelons: ", n);
scanf("%d", &cur);
min = max = cur;
for (i = 1; i < n; i++) {
if (scanf("%d", &cur) != 1) {
printf("error in scanf\n");
exit(EXIT_FAILURE);
}
if (cur < min)
min = cur;
if (cur > max)
max = cur;
}
printf("Ivan Vasilyevich: %d\nMother: %d\n", max, min);
return 0;
}
Example Session 1:
Enter number of watermelons: 5
Enter weights of 5 watermelons: 2 5 1 9 10
Ivan Vasilyevich: 10
Mother: 1
Example Session 2:
Enter number of watermelons: 1
Ooops!
Example Session 3:
Enter number of watermelons: 30001
Please enter less than 30000 watermelons.
do not modify your original array
initialize your gw and lw
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, w[30000], gw, lw;
scanf("%d", &n);
n = abs(n);
for (i = 0; i < n; i++)
{
scanf("%d", &w[i]);
}
if (n >= 2)
{
gw = w[0];
for (i = 0; i < n; i++)
{
if (gw < w[i]) gw = w[i];
}
lw = w[0];
for (i = 0; i < n; i++)
{
if (lw > w[i]) lw = w[i];
}
printf("%d %d", lw, gw);
return 0;
}
else
{
printf("Ooops!");
return 0;
}
}

For loop "<" vs "<=" print format issues in program

I am learning C on my own with a book and I cannot for the life of me figure out how to solve this exercise. I'm obviously looking at it in the wrong way or something. Here is an explanation below.
Listed below are some functions and the main function at the bottom. This program is compiled to generate a certain number of random numbers and determine the min and the max of the random numbers. If you copy and paste this code, you will see how it works. Anyways, an exercise asks me to go to the function "prn_random_numbers()" and change the for loop from "for (i = 1; i < k; ++i)" to for (i = 2; i <= k; ++i). This causes the first line format to print incorrectly. The exercise is to further modify the program in the body of the for loop to get the output to be formatted correctly.
To sum it up, the "prn_random_numbers()" function is written to print out 5 random numbers before moving to the next line. Hence the" i % 5" if statement. Now, for some reason, when you make the slight adjustment to the for loop, as the exercise asks above, it causes the first line to only print 4 numbers before moving to the next line. I have tried a number of things, including trying to force it to print the 5th number, but it only duplicated one of the random numbers. I even tried "i % 4" to see if it would print 4 numbers for each row, but it only prints 3 numbers for the first row instead of 4! So it always prints one less number on the first line than it is supposed to. I have n clue why it is doing that and the book does not give an exercise. Do you have any idea?
Bear with me if you think this is a stupid question. I am just learning on my own and I want to make sure I have a good foundation and understand everything as I learn it, before moving forward. I appreciate any help or advice!
prn_random_numbers(k) /* print k random numbers */
int k;
{
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 1; i < k; ++i)
{
if (i % 5 == 0)
printf("\n");
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main()
{
int n;
printf("Some random numbers are to be printed.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
while (n < 1)
{
printf("ERROR! Please enter a positive integer.\n");
printf("How many would you like to see? ");
scanf("%d", &n);
}
prn_random_numbers(n);
return (EXIT_SUCCESS);
}
the following proposed code:
properly initializes the random number generator
cleanly compiles
properly checks for and handles errors
performs the desired functionality
avoids having to list instructions twice
follows the axiom: Only one statement per line and (at most) one variable declaration per statement.
does not use undefined functions like: max() and min()
and now the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void prn_random_numbers(int k)
{
int count = 1;
int r;
int smallest;
int biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for ( int i = 2; i <= k; i++, count++)
{
if (count % 5 == 0)
{
count = 0;
printf("\n");
}
r = rand();
smallest = (r < smallest)? r : smallest;
biggest = (r > biggest)? r : biggest;
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}
int main( void )
{
int n;
srand( (unsigned)time( NULL ) );
do
{
printf("Please enter a positive integer, greater than 0.\n");
printf("How many would you like to see? ");
if( scanf("%d", &n) != 1 )
{
fprintf( stderr, "scanf for number of random numbers failed\n" );
exit( EXIT_FAILURE );
}
} while( n < 1 );
prn_random_numbers(n);
// in modern C, if the returned value from `main()` is 0 then no `return 0;` statement needed
}
a typical run, no input problems is:
Please enter a positive integer, greater than 0.
How many would you like to see? 20
98697066 2110217332 1247184349 421403769 1643589269
1440322693 985220171 1915371488 1920726601 1637143133
2070012356 541419813 1708523311 1237437366 1058236022
926434075 1422865093 2113527574 626328197 1618571881
20 random numbers printed.
Minimum: 98697066
Maximum: 2113527574
Try to use a debugger to solve your problem, it's easy to use and really helpfull :)
SOLUTION:
Your i variable don't count the number of numbers because it is initialize at 1 (in the for statement), so you need to declare a new variable to count properly.
If you have still a problem:
void prn_random_numbers(int k)
{
int count = 1;
int i, r, smallest, biggest;
r = smallest = biggest = rand();
printf("\n%12d", r);
for (i = 2; i <= k; i++, count++) {
if (count % 5 == 0) {
count = 0;
printf("\n");
}
r = rand();
smallest = min(r, smallest);
biggest = max(r, biggest);
printf("%12d", r);
}
printf("\n\n%d random numbers printed.\n", k);
printf("Minimum:%12d\nMaximum:%12d\n", smallest, biggest);
}

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

How to successfully output a function call?

My assignment is to check if a number is prime, but I have to use three sections to do it. The first is the main body of code and that is followed by two functions. The first checks if the number is even, and the second checks if it is prime. I know this is a rather tedious way to check if a number is prime but it is meant to get us introduced to functions and function calls!
UPDATE
I have gotten it all to work besides printing the smallest divisor of a non prime number. I thought using i from the second function would work but it will not output. I have copied by code below -- please help if you have any suggestions!
#include <stdio.h>
#include <math.h>
int even (int);
int find_div (int);
int main() {
int num, resultEven, resultPrime, i;
printf("Enter a number that you think is a prime number (between 2 and 1000)> \n");
scanf("%d", &num);
while (num < 2 || num > 1000) {
if (num < 2) {
printf("Error: number too small. The smallest prime is 2.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else if (num > 1000) {
printf("Error: largest number accepted is 1000.\n");
printf("Please reenter the number > \n");
scanf("%d", &num);
}
else {
}
}
resultEven = even(num);
resultPrime = find_div(num);
if (resultEven == 1) {
printf("2 is the smallest divisor of %d. Number not prime\n", num);
}
else if (resultPrime == 1) {
printf("%d is the smallest divisor of %d. Number not prime\n", i, num);
}
else {
printf("%d is a prime number.\n", num);
}
return 0;
}
int even(int num) {
if (num % 2 == 0) {
return 1;
}
else {
return 0;
}
}
int find_div(int num) {
int i;
for (i = 2; i <= (num/2); i++) {
if (num % i == 0) {
return 1;
}
if (num == i) {
return 0;
}
}
return i;
}
I would create a function for Wilsons theorem (p-1)! = 1 (mod p) iff p is prime, first off, to make the functions nice and easy you will only need the one. for numbers less than 1000 it should work fine.
something like,
//it will return 1 iff p is prime
int wilson(int p)
{
int i, result = 1;
for (i = 0; i < p; i++)
{
result *= i;
result = result % p;
}
return result;
}
however if your not printing check that you have included, at the top of your file
#include <stdio.h>
your
resultEven = even(num)
needs a ; at the end but that was mentioned in the comments, besides that your methodology though odd is correct, also you do not need the empy else, that can simply be removed and your good
UPDATE:
//if return value == 1 its prime, else not prime, and
//return value = smallest divisor
int findDiv(int p)
{
int i= 0;
for (; i <= n/2; i++)
{
//you number is a multiple of i
if (num % i == 0)
{
//this is your divisor
return num;
}
}
//1 is the largest divisor besides p itself/smallest/only other
return 1;
}
your function call is correct but you need a semi colon (;) at the end of:
resultEven = even(num)
otherwise this program effectively checks for evenness. To check for prime one way is to ensure the number has no factors other than one and itself. This is done by finding the div of every whole number from 2 to half of the number being tested using a for loop. If a number produces a div of 0 then it is not prime because t has a factor other than 1 and itself.

Finding the largest even digit in a given integer

I am taking an online C class, but the professor refuses to answer emails and I needed some help.
Anyways, our assignment was to write a program that takes an integer from the user and find the largest even digit and how many times the digit occurs in the given integer.
#include <stdio.h>
void extract(int);
void menu(void);
int main() {
menu();
}
void menu() {
int userOption;
int myValue;
int extractDigit;
do {
printf("\nMENU"
"\n1. Test the function"
"\n2. Quit");
scanf("%d", &userOption);
switch (userOption) {
case 1:
printf("Please enter an int: ");
scanf("%d", &myValue);
extractDigit = digitExtract(myValue);
break;
case 2:
printf("\nExiting . . . ");
break;
default:
printf("\nPlease enter a valid option!");
}
} while (userOption != 2);
}
void digitExtract(int userValue) {
int tempValue;
int x;
int myArr[10] = { 0 };
tempValue = (userValue < 0) ? -userValue : userValue;
do {
myArr[tempValue % 10]++;
tempValue /= 10;
} while (tempValue != 0);
printf("\nFor %d:\n", userValue);
for (x = 0; x < 10; x++) {
printf("\n%d occurence(s) of %d",myArr[x], x);
}
}
I have gotten the program to display both odd & even digit and it's occurrences.
The only part that I am stuck on is having the program to display ONLY the largest even digit and it's occurrence. Everything I've tried has either broken the program's logic or produces some weird output.
Any hints or ideas on how I should proceed?
Thanks ahead of time.
Run a loop from the largest even digit to smallest even digit.
for (x = 8; x >=0; x-=2)
{
if(myArr[x]>0) //if myArr[x]=0 then x does not exist
{
printf("%d occurs %d times",x,myArr[x]);
break; //we have found our maximum even digit. No need to proceed further
}
}
Note:To optimize you should count and store occurrences of only even digits.
Why do you even use the extra loop? To find the largest even digit in an integer and the number of its occurences, a modification to the first loop would suffice.
Consider the following (untested, but I hope you get the idea):
int tempValue;
int x;
int myArr[10] = { 0 };
int maxNum = 0;
tempValue = (userValue < 0) ? -userValue : userValue;
do {
int currNum = tempValue % 10;
myArr[currNum]++;
tempValue /= 10;
if (currNum % 2 == 0 && currNum > maxNum)
maxNum = currNum;
} while (tempValue != 0);
After this, maxNum should contain the largest even digit, and myArr[maxNum] should be the number of its occurences.

Resources