Prime Numbers Exercise - Loop Issue C++ -
i trying solve exercise written in stroustrup's book calculating , printing if number between 1 , 100 prime number or not.
my code seems work but, when prints values on screen, starts 6 , not 2.
i have tried figure out why not able understand reason of that.
can lend me hand?
thank much!
// prime numbers.cpp : definisce il punto di ingresso dell'applicazione console. // #include "stdafx.h" #include "std_lib_facilities.h" vector<int> primes = { 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97 }; int primecheck(int x) { (int : primes) { if (x <= primes[i]) break; if (primes[i] == x) return 1; while (x % primes[i] != 0) { --i; if (i < 0) { return 1; break; } else { if (x % primes[i] == 0) return 2; } } } } int _tmain(int argc, _tchar* argv[]) { (int = 1; <= 100; ++i) { if (primecheck(i) == 1) { cout << << " prime number." << endl; } else { if (primecheck(i) == 2) { cout << << " not prime number." << endl; } } } keep_window_open(); return 0; }
your code wrong , should rewrite it. not paths have return statement , must use instead of prime[i]
there's simple working code:
int primecheck(int x) { (int prime : primes) { if (x < prime) { return 2; }else if (x == prime) { return 1; } return 2; }
Comments
Post a Comment