Prime number algorithm Objective C explanation please - objective-c

Hi sorry for my bad english, i have a question guys, i'm learning objective c and i'm learning booleans right now, my question is: why when running the second loop in the code, the number 2 is taken as prime, i mean, as i see it p takes the value 2 in the first loop, then d start at 2 but then it says d < p, i think that's p-1 (2-1 = 1), so how that code works, it doesn't make sense, i understand why it works with any other number greater than 2 but i don't get it why it works with the number 2!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
#autoreleasepool
{
int p, d;
BOOL isPrime;
for (p = 2; p <= 50; p++)
{
isPrime = true;
for (d = 2; d < p; d++)
{
if (p % d == 0)
isPrime = false;
}
if (isPrime == true)
NSLog(#"%i", p);
}
}
return 0;
}

The first loop starts p=2, then the inner loop take d=2 and then check if d<p. This condition is false because d=2 P=2. This means the first inner loop doesn't run and isPrime is always true at the first loop of p.

A prime number is divisible by 1 or itself.
So we check divisibility for all the numbers between 1 and the number.
That is why we start we 2 and till number-1
for(d = 2; d < p; d++ )

Prime numbers are the numbers which are not divisible by any other number.They are divisible by itself only (eg 2,3,5,7)
If we will only check till the half of number, since more than half of number will not divide it.
-(BOOL)checkNumberPrimeNumber:(int)number{
int i; BOOL flag=false;
for (i=2; i<number/2; i++) {
if (number%i==0) {
flag=true;
break;
}
}
if (flag==true) {
NSLog(#"%d is Not Prime Number",number);
}
else{
NSLog(#"%d is Prime Number",number);
}
return YES;
}

Related

BIG WEIRD ANSWER in a MATRIX multiplication program

this is a program to multiply 2 matrixes which comes in maths, but dont know why, am getting answers like "-1282230" or some weird numbers. I would like to know what is causing it and how could i fix it? THANK YOU!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int m[3][3],m2[3][3],i,je,k,ans[3][3],sum;
// taking inputs from the user for matrix1
printf("Enter the numbers for first matrix");
je=0;
for(i=0;i<3;i++){
printf(" for row %d\n",i+1);
for(je=0;je<3;je++){
scanf("%d",&m[i][je]);
}
}
// taking inputs from the user for matrix2
printf("Enter the numbers for second matrix");
je=0;
for(i=0;i<3;i++){
printf(" for row = %d\n",i+1);
for(je=0;je<3;je++){
scanf("%d",&m2[i][je]);
}
}
// multiplication OR MATRIX CMS HERE;
sum = 0;
for(k=0;k<9;k++){
for(i=0;i<3;i++){
for(je=0;je<3;je++){
sum = m[k][je] * m2[je][i];
ans[i][je] = sum;
}
}
k++;
}
// it ENDS;
puts("ANSWER IS:: \n");
// Displaying answer, matrix;
for(i=0;i<3;i++){
for(je=0;je<3;je++){
printf("%d\t",ans[i][je]);
}
printf("\n");
}
return 0;
}
Here's a working solution. One of the problem with your code is that you aren't setting the sum to 0 after each multiplication.
#include <stdio.h>
int main() {
int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n"); scanf("%d%d", &m, &n); printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n"); scanf("%d%d", &p, &q);
if (n != p)
printf("The matrices can't be multiplied with each other.\n"); else {
printf("Enter elements of second matrix\n");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0; }

Confusion about my QuickSort algorithm & Mergesort algorithm

I am currently conducting empirical studies to evaluate the run-time complexities of the quicksort, and mergesort algorithms. To do this I run a random number generator that stores whatever amount of numbers I specify in a binary file. The ranges of those numbers are from 1-1,000,000.I then run tests of each algorithm starting from 100,000 numbers, incrementing by 50,000 each time, until 1,000,000 numbers are sorted on the last run. So 20 tests each. I have successfully completed each algorithm but my results are kind of puzzingly. This is a graph showing my results.
I understand that quicksort has a worst case of O(n2) time, but typically O(n·lg(n)) time. Mergesort has Θ(n·lg(n)) time.
Also I would like to note that when I started the timer I just used clock() from time.h, and calculated the time elapsed. I started my timer one line of code before I called my sorting function.
What I dont understand is how my graph shows mergesort is always double the time, and reaching triple the time to sort numbers compared to quicksort.
My only thought is that for my mergesort algorithm every time I divide my array in half I use malloc to create a new integer array for each half. Of course this means a large amount of calls are made to malloc considering the number sizes I am sorting.
int* mergeSort(int* nums, int size){
int* left;
int* right;
int middle = size/2;
if(size <= 1)
return nums;
split(nums, size, &left, &right, middle);
//I dont understand why the code below wouldnt work in place of the split()
//when i run it, in main, nothing gets printed out. I guess i lose my pointer to the beginning of my array.
//left = nums;
//right = nums+middle;
left = mergeSort(left, middle);
right = mergeSort(right, size - middle);
merge(nums,left,right,middle,size - middle);
free(left);
free(right);
return nums;
}
void split(int* nums, int size, int** left, int** right, int middle){
int *lft = (int*) malloc ((sizeof(int) * middle));
int *rght = (int*) malloc ((sizeof(int) * size - middle));
int mid = middle;
int upMid = size - middle;
int i;
for(i=0; i < mid; i++)
lft[i] = nums[i];
for(i=0; i < upMid; i++)
rght[i] = nums[i+middle];
*left = lft;
*right = rght;
}
void merge(int* num, int* left, int* right, int sizeLeft, int sizeRight){
int i,j,k,n;
i=j=k=0;
n=sizeLeft + sizeRight;
while(k < n){
if(i< sizeLeft){
if(j<sizeRight){
insert(num,left,right,&i,&j,&k);
}
else{
append(num, left, sizeLeft, &i, &k);
}
}
else{
append(num,right,sizeRight,&j,&k);
}
}
}
void insert(int* num, int* left, int* right, int* i, int* j, int* k){
/*int i,j,k,n;*/
if(left[*i]<right[*j]){
num[*k] = left[*i];
(*i)++;
}
else{
num[*k] = right[*j];
(*j)++;
}
(*k)++;
}
void append(int* num, int* half, int sizeHalf, int* i, int* k){
while(*i < sizeHalf){
num[*k]= half[*i];
(*i)++; (*k)++;
}
}
I would greatly appreciate any feedback on this question of mine, and any advice on maybe making my mergesort function more efficient. Thanks!!
I have implemented a merge sort algorithm, you can have a look. I malloc a bak array at the beginning of mergeSort and every merge use the it afterwards.
#include <string>
#include <stdlib.h>
void _mergeSort(int *array, int *bakArray, int len) ;
void mergeSort(int *array, int len)
{
int *bak = (int *)malloc(sizeof(int)*len) ;
_mergeSort(array, bak, len) ;
free(bak) ;
}
void _mergeSort(int *array, int *bakArray, int len)
{
if (len >= 2) {
int leftLen = len/2 ;
_mergeSort(array, bakArray, leftLen) ;
_mergeSort(array+leftLen, bakArray, len-leftLen) ;
int *pa = array ;
int *pb = array+leftLen ;
int aIndex = 0 ;
int bIndex = 0 ;
while (aIndex < leftLen && bIndex < len-leftLen) {
int a = pa[aIndex] ;
int b = pb[bIndex] ;
if (a < b) {
bakArray[aIndex+bIndex] = a ;
++aIndex ;
} else if (a == b) {
bakArray[aIndex+bIndex] = a ;
bakArray[aIndex+bIndex+1] = a ;
++aIndex ;
++bIndex ;
} else {
bakArray[aIndex+bIndex] = b ;
++bIndex ;
}
}
if (aIndex < leftLen) {
memcpy(bakArray+aIndex+bIndex, pa+aIndex, sizeof(int)*(leftLen-aIndex)) ;
} else if (bIndex < len-leftLen) {
memcpy(bakArray+aIndex+bIndex, pb+bIndex, sizeof(int)*(len-leftLen-bIndex)) ;
}
memcpy(array, bakArray, sizeof(int)*len) ;
}
}
static const int MaxArraySize = 100 ;
int main()
{
srand(time(NULL)) ;
int array[MaxArraySize] ;
for (int i = 0 ; i < MaxArraySize; ++i) {
array[i] = rand() % 10000 ;
}
mergeSort(array, MaxArraySize) ;
for (int i = 0 ; i < MaxArraySize; ++i) {
printf("%d ", array[i]) ;
}
printf("\n") ;
return 0 ;
}

I'm trying to figure out how to calculate if a number is prime or not [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
ive refined it a bit. Can someone change it to the correct way for me?
i also introduced a new variable isPrime i guess this is a bit better
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
int p = 7;
int d, isPrime = 0;
if (p % 2 != 0)
{
for (d = 2; d < p; d++) {
p % d;
}
if (p % d == 0)
{
isPrime = 1; //not prime
}
if (p % d != 0)
{
isPrime = 2; //is prime
}
if (isPrime == 1)
{
NSLog(#"its not prime");
}
if (isPrime == 2) {
NSLog(#"its prime");
}
}
else
NSLog(#"sorry");
}
return 0;
}
There's the well-known Sieve of Eratosthenes, but if you are writing a program that is just going to take one number as input and decide whether it's prime, the Sieve does more than you need (it finds all primes less than some value of your choice) so it may not be your most efficient choice of algorithm.
A couple other things about finding primes:
If you find that p is not even, you only have to try dividing it by odd numbers, that is, 3, 5, 7, 9, etc. (Yes, once you know it's not divisible by 3, technically you know it's not divisible by 9, but it may not be worthwhile or even efficient to account for such things in your algorithm.)
You don't have to try anything larger than sqrt(p) as a divisor. If you haven't found a divisor by then, you never will (except for 1 and p itself).
If you find a number that divides p, you can say immediately that p is not prime. (You might want to make sure you exit any loops then, too, otherwise you might end up printing the announcement that p is not prime more than once.)
... But you must never say that p is prime until the end of your algorithm, after all loops have completed. Until then, the most you can say is you haven't yet found a proof that p is not prime.
Above loop is fine , but you have to start from 3 rather than 2.
This is pseudo code for prime number calculation :
int num = 11;
NSString * res = null;
for(int i = 2 ;i<num ;i ++)
{
if(num%i == 0)
{
res = #"This is not a prime number";
break
}
else{
res = #"This is prime number";
}
}
try this
int p = 7;
int d, isPrime = 2;
if (p % 2 != 0)
{
for (d = 2; (d < p) && (isPrime == 2); d++) {
if (p % d == 0)
{
isPrime = 1; //not prime
}
if (p % d != 0)
{
isPrime = 2; //is prime
}
}
if (isPrime == 1)
{
NSLog(#"its not prime");
}
if (isPrime == 2) {
NSLog(#"its prime");
}
}
else
NSLog(#"sorry");

How to count the number of repetitions that while does?

I am doing a year of college and am having MUCH difficulty at a specific point ....
I need to make a code that reads the population of the U.S. and Brazil, knowing that the population of the U.S. is higher than in Brazil.
The issue is I need to count the number of the while loop, after all if 1 means 1 more year if it is 2 years older is 2 and so on. the code is here and is objective-c...
int pAmericana, pBrasileira, ano;
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSLog(#"What year is it?");
scanf("%i", &Ano);
NSLog(#"which the American people?");
scanf("%i", &pAmericana);
NSLog(#"which the Brazilian people?");
scanf("%i", &pBrasileira);
while (pAmericana >= pBrasileira) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
}
//FAILURE TO KNOW HOW TO COUNT HOW OFTEN HAPPENS THE LOOP .....
}
return 0;
}
You can use a counter inside the loop:
int i = 0;
while (pAmericana >= pBrasileira) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
i++;
}
NSLog(#"Loop count %i", i);
Adding a count variable to the while loop works. But you can also use a for loop:
int i = 0;
for (; pAmericana >= pBrasileira; i++) {
pAmericana=(pAmericana*0.2)+pAmericana;
pBrasileira=(pBrasileira*0.4)+pBrasileira;
}
NSLog(#"Loop executed %d times", i);
You must declare the variable before the for loop so its value is available after the loop.
Note - you can change the calculations to:
int i = 0;
for (; pAmericana >= pBrasileira; i++) {
pAmericana *= 1.2;
pBrasileira *= 1.4;
}
int i = 0 before the while, i++; in the while loop, NSLog(#"Loops: %d", i); after the loop.
You can declare an integer variable outside the while loop then increment it within the loop, like this:
int i = 0; // Initialise the counter
while (pAmericana >= pBrasileira) {
...
i++; // Increment the counter
}

greatest common factor on objective c

I'm new to objective c and I would like to know if there is a method for greatest common factor
gcf() for example so you get the idea
There's no out of the box function. Since Objective-C is a superset of C, you can grab an existing library or set of functions and include it where necessary.
Based on http://www.idevelopment.info/data/Programming/data_structures/c/gcd/gcd.c, you might do this:
// gcd.h
int gcd(int m, int n);
// gcd.c
int gcd(int m, int n) {
int t, r;
if (m < n) {
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0) {
return n;
} else {
return gcd(n, r);
}
}
Include that file whenever you should wish to use the gcd function:
#import "gcd.h"
There is no built in method, but the Euclidean algorithm is easy to implement, and quite efficient.
The binary GCD algorithm can be slightly more efficient. This link has C code implementing it.
By far the most elegant solution I have come across (non-recursive of course):
int gcd (int a, int b){
int c;
while ( a != 0 ) {
c = a; a = b%a; b = c;
}
return b;
}
Source.
Just putting damian86's answer into Objective-C style (reference to self assumes context of an object, modify accordingly, you could make this a category, etc):
-(int)greatestCommonDivisorM:(int)m N:(int)n
{
int t, r;
if (m < n) {
t = m;
m = n;
n = t;
}
r = m % n;
if (r == 0) {
return n;
} else {
return [self greatestCommonDivisorM:n N:r];
}
}