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.
Related
I've been trying to write a recursive function that scans a series of numbers and returns the sum of the numbers in odd indexes minus the sum of numbers in even indexes.
biggest problems: the function is not supposed to receive any parameters when called upon; and I have to do it in one function.
Edit: so, I wrote this code and it seems to work for the most part, but the problem is I wasn't supposed to send any parameters with the function (f wasn't supposed to exist)
void Ex1() // this is sort of like the main
{
int f = 1, res;
res = sumofodd_even(f);
printf("sum is: %d\n", res-1);
}
int sumofodd_even(int flag)
{
int num = 0;
printf("enter a number. to stop enter -1 >> \n");
scanf_s("%d", &num);
if (num != -1)
{
if (flag == -1)
num *= -1;
return num + sumofodd_even((-1) * flag);
}
}
btw: can't use pointers or arrays...
will appreciate any help.
One approach might be to just use a boolean flag that gets flipped at every recursion:
#include <stdbool.h>
#include <stdio.h>
int sumofodd_even(const bool odd) {
printf("enter a number. to stop enter -1 >> ");
int num = 0;
scanf("%d", &num);
if (num == -1) {
return 0; // breaks the recursion
}
num *= odd ? 1 : -1;
return num + sumofodd_even(!odd);
}
int main(void) {
printf("sum is: %d\n", sumofodd_even(false)); // zero is even, thus we start with odd == false
return 0;
}
you can use odd to mark if the read value should be treated as an odd number or as an even number, and thus change its sign accordingly.
Alternative to counting iterations or flipping a flag is to simply use two functions. After all, your algorithm has two states: process an even-indexed number, or process an odd-indexed number. Rather than have one function with an if statement, just use a function for each state, and have those functions transition between states by calling on each other.
int sum_of_odd() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_even() + num;
}
int sum_of_even() {
// <Ask user for input>
if (num == -1) {
return 0;
}
return sum_of_odd() - num;
}
And of course you'd start the algorithm by calling sum_of_odd(), since the first number is odd-indexed (unless you want to "index by zero").
So I have this exercise where I need to show the N first prime numbers, but I need to specifically create a function to know if the number is a prime number
#include <stdio.h>
#include <stdlib.h>
int prime(int num){
int cont,i,j=0,b;
b=num;
do{
j++;
i=0;
for(cont=1;cont<j;cont++){
if(j%cont == 0)
i++;
}
if(i == 1){
return(j);
c=j;
b--;
}
} while (b > 0);
}
int main(){
int *v,n,cont;
do{
printf("Input an integer: ");
scanf("%d",&n);
} while (n <= 0);
v = (int *)malloc(n * sizeof(int));
for(cont=0;cont<n;cont++){
v[cont] = prime(n);
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
}
The problem with the way i've done this is that the variable J is aways being set to 0 when i call the function again, i've tried to set something like c=j so when the program return to the prime function it would have the 'previous' j value but it gets a weird random number. So I wanted to know if is there a way to 'return' the result in the main function to the prime function, i couldn't find anything that helped me, not that i could understand at least
Your function prime() is not working as intended and there are many other errors -
1) Since smallest prime is 2, variable cont should start from 2.
2) scanf need not be in a loop in this case
3) Enter values in v only when cont is confirmed a prime.
See this function prime2( not optimize though for clarity):
bool prime2(int n)
{
for(int i = 2 ; i<n-1;i++)
if( n% i == 0) return false;
return true;
}
int main(){
int *v,n,cont,cc=0;
printf("Input range: ");
scanf("%d",&n);
v = malloc(n * sizeof(int));
for(cont=2;cc<n;cont++){
if( prime2(cont) == true )
{
v[cc] = cont;
cc++;
}
}
for(cont=0;cont<n;cont++){
printf("%d ",v[cont]);
}
delete v;
}
Output:
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;
}
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.
so my task is as follows: Construct a do-while() loop, which continues to prompt the user for an integer, and determines the sum of integers entered, until a prime number is encountered. The prime number should not be included in the sum. Show all variable declarations.
I have all of the variable add up correctly however cannot seem to get the function to stop on a prime number. To try to correct this I made the variable "primecheck" and set it to 2++ thinking that it would be every integer above 2 (obviously not possible but one could hope). any assistance would be much appreciated!
int main (void)
{
int sum = 0, num = 0, i = 0, primecheck = 0, two = 2;
primecheck = two++;
do
{
printf ("Enter an integer: ");
scanf ("%d", &num);
if (num % primecheck == 0 && primecheck != num)
{
sum += num;
}
} while (num % primecheck == 0 && primecheck != num);
i = sum;
printf("%s%d%s", "Sum = ", i, "\n");
}
One possibility would be to introduce a function which performs the primality check, which could be done by using check divisions by all smaller numbers and terminate the loops as soon as a prime number is found. An implementation can be found following this link; the code can be refactored to the follwing function for primality testing. The function returns 1 if n is prime and 0 otherwise. The implementation uses an explicit while loop as the requirements apparently demands it.
int is_prime(int n)
{
int i=3;
int flag=0;
if (n%2==0)
{
return 0;
}
do
{
if (n%i==0)
{
flag=1;
break;
}
i+=2;
}
while (i*i<=n);
return flag;
}