Project Euler # 10 in Objective C - objective-c

I'm trying to solve Problem 10 in Project Euler, and while I thought I had it, its saying my answer is incorrect. The question is as follows:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
And my code:
int sum;
#interface Prime : NSObject
-(BOOL)isPrime:(int)arg1;
#end
#implementation Prime
-(BOOL)isPrime:(int)arg1 {
if (arg1 == 1) {
NSLog(#"Given 1");
return NO;
}
for (int i = 2; i < arg1; i++) {
if (arg1 % i == 0) {
return NO;
}
}
sum += arg1;
return YES;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
Prime* primeObject = [[Prime alloc] init];
for (int i = 0; i < 2000000; i++) {
[primeObject isPrime:i];
}
NSLog(#"Sum of primes is %i", sum);
}
}
This code outputs 'Sum of primes is 1179908154' which Project Euler says is incorrect. Help?

The problem is that the sum does not fit into a 32-bit integer. You should use long long instead.

Just a guess, you should try to:
Initialise the sum variable to 0.
Try not to use a global variable like sum that can be accessed from anywhere, in this case do the sum in the main loop instead of in the isPrime method.
Maybe that'll give you the right answer.

You are using int for getting result, so it is wrong.
I'm using long int instead, that is enough for this case.
Here is my code, and it works fine:
int inputNumber = 2000000;
long int result = 0;
for (int i = 2; i < inputNumber; i++) {
BOOL isPrime = YES;
for (int j = 2; j <= sqrt(i); j++) {
if (i%j==0) {
isPrime = NO;
break;
}
}
if (isPrime) {
result += i;
}
}
Result is: 142913828922

Related

Populating table causes unexpected results

I am totally stumped. I have been debugging this for hours. I am allocating a table of 100 UInt32s by 100. I am loading a table of values and writing them to the 2D array. For some bizarre reason when I get to row 67, column 0 the writes appear to wrap back around to row 0 element 0.
I have rewritten it to allocate a list of arrays rather than a single malloc. Same exact behavior. I have tried doing math for the index: _map[row * 100 + column] instead of _map[i,j] and that leads to other strange behavior. I was thinking maybe something is overflowing, but I can't see how since the data is so small. Obviously I am doing something stupid but I just... can't.. see it.
Code snippet:
_map = malloc(100 * 100 * sizeof(UInt32));
int i = 0;
for (i=0; i <_columns; i++)
{
columnList = [[lineList objectAtIndex:i] componentsSeparatedByString:#","];
int j = 0;
for (j=0; j < _rows; j++)
{
UInt32 dataInt = atoi([[columnList objectAtIndex:j] UTF8String]);
// Convert the data
NSDictionary* tDict = [fileMap objectForKey:[NSString stringWithFormat:#"%i", dataInt]];
int newVal = [[tDict objectForKey:#"convert"] integerValue];
_map[i,j] = (UInt32)newVal;
UInt32 y = _map[i,j];
// This trips at row 67 element 0
if (_map[0,0] != 1)
printf("Here\n");
}
}
Any help would be absolutely most awesomely appreciated.
As I mention below, this code gives the same problem in that it corrupts the first line. As if every row is the same row:
int** testMap = malloc(100 * 100 * sizeof(int));
int data = 0;
for (int i = 0; i<100; i++)
{
for (int j = 0; j < 100; j++)
{
testMap[i, j] = data;
data++;
printf("(%i, %i)", i,j);
}
printf ("\n");
}

Expected expression error - Objective c

I'm doing a tutorial from this book: "Objective-C 2.0 Essentials 3rd edition" by Neil Smyth. I have tried repeatedly but keep getting the same "Expected expression" error even though the books version claims to run. I've checked way too many times and my version is exactly the same as the books. Please, can someone help me. Code below:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
#autoreleasepool {
int x;
int j = 54321;
for (x = 0; x < 10; x++) {
}
int j = x + 10;
NSLog (#"Variable j in for loop is %i", j);
NSLog (#"Variable j outside for loop is %i", j); /* I GET AN ERROR STATING " EXPECTED EXPRESSION HERE*/
}
return 0;
}
The line
NSLog (#"Variable j outside for loop is %i", j);
contains a lot of invisible characters (UTF-8 sequence EF BF BC = OBJECT REPLACEMENT CHARACTER) between the Tab and the "NSLog".
Deleting and rewriting that line should help.
OP's code opened in hexa editor:
Format your code better; if you do the misplaced } in the code becomes obvious:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
#autoreleasepool {
int x;
int j = 54321;
for (x = 0; x < 10; x++) {
int j = x + 10;
NSLog (#"Variable j in for loop is %i", j);
}
 NSLog (#"Variable j outside for loop is %i", j);
}
return 0;
}
EDIT The invisible characters as pointed out by #MartinR are also an issue (that I didn't notice). So there are two errors in your code.

exc_bad_access (code= 2 address =0x0)

I am new to this, trying to make an Minesweeper iphone app
i used a IBButton to Reset mine fields
which is a 2 by 2 matrix of a struct
- (IBAction) Reset {
for (int x = 0 ; x < 10 ; x ++) {
for (int y = 0 ; y < 10 ; y++ ) {
f[x][y]->isOpen = NO;
f[x][y]->display = 0; //Going to make a search function for finding Number of mines next to it
int random = arc4random()%10;
if (random < 2) {
f[x][y]->isMine = YES;
} else {
f[x][y]->isMine = NO;
}
}
}
so i get the the error at the very first line of my for loop
f[x][y]->....
what did i do wrong here?
/edit
This is how i declared my f
struct feild *f[10][10];
struct feild{
bool isOpen;
bool isMine;
int display;
}
You haven't allocated any space for f, so f[x][y] will just contain junk memory and then the ->isOpen = NO access will blow up.
you need to do something like
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
f[i][j] = malloc(sizeof(struct feild));
}
}
before your code.

Icomplete implementation and Pointer conversion error.

Compiler warning(1): Incomplete implementation
I've compared my .h and .m files to see any inconsistencies or spelling mistakes between whats declared and implemented and can't find any.
Compiler warning(2): Incompatible integer to pointer conversion sending 'NSInteger*' (aka 'int*') with and expression of type 'int'.
I've been mucking about with asterisks for 25 minutes in all sorts of combinations and the compiler is still unhappy.
#import "Game.h"
#import "stdlib.h"
const int MAXRAND = 15;
const int MAXCOL = 7;
const int MAXROW = 9;
NSInteger gameState[MAXROW][MAXCOL];
NSInteger answerBoard[MAXROW][MAXCOL];
#implementation Game//compiler warning 1
-(void)init:(NSInteger*) rows: (NSInteger*) columns: (NSInteger*) operators:(NSInteger*) operands{
NSLog(#"init sent");
numRows = *rows;
numColumns = *columns;
numOperators = *operators;
numOperands = *operands;
//seed random number generator
//generate rand nums for operands
int operandList[numOperands];
for (int i = 0; i < numOperands; i++) {
srandom(time(NULL));
operandList[i] = (random()%MAXRAND);
}
//generate state and answer board
BOOL gameState[numRows][numColumns];
NSInteger answerBoard[numRows][numColumns];
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numColumns; j++) {
gameState[i][j] = NO;
answerBoard[i][j] = (operandList[random()%numOperands])+
(operandList[random()%numOperands])-
(operandList[random()%numOperands]);
}
}
}
-(void)updateGame:(NSInteger*)enteredNum{
NSLog(#"updateGame sent");
for (int i = numColumns; i > 0; i--) {
for (int j = numRows; j > 0; j--) {
if (gameState[i][j] == NO){
if (*enteredNum == answerBoard[i][j]){
gameState[i][j] = YES;
}
}
}
}
}
#end//Game
#import <Foundation/Foundation.h>
#interface Game : NSObject
{
NSInteger numRows, numColumns, numOperators, numOperands;
}
-(void)init:(NSInteger*) rows: (NSInteger*) columns: (NSInteger*) operators:(NSInteger*) operands;
-(void)updateGame:(NSInteger*) enteredNum;
#end
Where the instance of my class is declared and initialized:
NSInteger *rows = 7, *columns = 6, *operators = 2, *operands = 6;//compiler warning 2
Game *game = [Game new];
[game init:rows :columns :operators :operands];
NSInteger *rows = 7, *columns = 6, *operators = 2, *operands = 6;
rows,columns, operators, operands are of type NSInteger *. You need to allocate memory and then need to place 7,6,2,6 in the memory locations they are pointing at. In C-terms,
int *ptr = 7; // Wrong. Because, ptr is pointing no where to keep 7 in that location.
Did you try?
NSInteger rows = 7, columns = 6, operators = 2, operands = 6;
And what is?
[Game new];
The compiler is probably expecting you to implement a function named new.
EDIT:
Try removing all '*' from your NSInteger's.

C logic error in for statement with break

Am running this C program, but instead of answering "The answer is 10", it sends back the message: "The answer is 0", even though it breaks at the right time.
Can you tell me what's wrong?
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
int i;
for(int i = 0; i < 12; i++){
printf("Checking i = %d\n", i);
if(i + 90 == i * i) {
break;
}
}
printf("The answer is %d.\n", i);
}
The problem is you have two i's.
int main (int argc, const char * argv[])
{
int i; //Declares outer i
for(int i = 0; i < 12; i++) //Declares a NEW i
{
printf("Checking i = %d\n", i);
if(i + 90 == i * i)
{
break;
}
}
printf("The answer is %d.\n", i); //Uses the outer i
}
Basic scope confusion: You have two different variables called i: One in the outer scope of the main function body, and another, overriding one inside the for loop.
The outer variable is uninitialized, so in fact you have undefined behaviour.
What you mean to say is this:
int i;
for (i = 0; i < 12; i++)
/* ^^^^^ use existing variable! */
{
printf("Checking i = %d\n", i);
if (i + 90 == i * i)
{
break;
}
}
Could it be the extra "int"? You're declaring another instance of "i" in the for loop that goes out of scope when the loop exits.
for(int i = 0; i < 12; i++){
You're creating another i here, which hides the i outside the scope of the for loop.
Change to:
int i;
...
for (i = 0; i < 12; i++){
Because you've got two DIFFERENT variables "i" - the one in the inner scope (which you increment from 0..11), and the one in the outer scope. You print the one in the outer scope.
SOLUTION:
change "for (int i=...)" to "for (i=...)"